日期getTime为较长的持续时间提供较低的值

时间:2015-02-04 21:10:08

标签: javascript game-physics craftyjs

我正在使用Date()。getTime来通过从keyup事件中减去keydown事件来测量按键的持续时间。但是,对于超过~500ms的按键,记录的时间似乎返回到较低的值。

这是JSFiddle http://jsfiddle.net/bdzaorw2/

$(document).ready(function(){

Crafty.init(window.innerWidth,window.innerHeight);
var player = Crafty.e();

//...

function horizontal(){

if(keyboard[38] && !player.jumping){
    player.v.velocity = 5;
    player.jumping = true;
}

if(keyboard[38] && player.jumping){
    var now = new Date();
    if( now.getTime() - keystart[38].getTime() < 500){
        player.v.velocity = 5;
    }
    document.getElementById("p").innerText = now.getTime() - keystart[38].getTime();
}


  setTimeout(horizontal, (frame * 1000) / timeMultiplier);
}


horizontal();


document.body.addEventListener("keyup", function (code) {
    keyboard[code.keyCode] = false;
});

document.body.addEventListener("keydown", function (code) {
    keyboard[code.keyCode] = true;
    var then = new Date();
    keystart[code.keyCode] = then;
});

});

2 个答案:

答案 0 :(得分:0)

尝试Event.timeStamp,看看它是否有所作为。 这是一个例子:

var number = event.timeStamp;

<html>
<head>

<title>timeStamp example</title>

<script type="text/javascript">
function getTime(event) {
  document.getElementById("time").firstChild.nodeValue = event.timeStamp;
}
</script>
</head>

<body onkeypress="getTime(event)">

<p>Press any key to get the current timestamp
for the onkeypress event.</p>
<p>timeStamp: <span id="time">-</span></p>

</body>
</html>

答案 1 :(得分:0)

我在你的代码中看到了一些错误: - 在keydown上你正在计算并重新计算Date.now()所以只是改变了这部分代码

keyboard[code.keyCode] = true;
var then = new Date();
keystart[code.keyCode] = then;

用这个:

var then = new Date();
if(!keyboard[code.keyCode]) { //only if not yet pressed it will ignore everything until keyup
    keyboard[code.keyCode] = true; //start movement
    keystart[code.keyCode] = then; //set time
}

这是改编的例子: http://jsfiddle.net/bdzaorw2/