我正在尝试根据时间和FPS制作一个角色。
我需要的是让我的角色跳跃持续 1 秒。现在我正在使用下面的代码,它使字符跳跃 1 秒。但问题是..如果 fps 是 60 个字符移动 60 像素,如果 fps 是 30,它只移动 30 像素......我该如何解决这个问题..
我需要字符在 60 秒内移动 60 像素,无论 fps 如何。
//Below is the requestanimation frame loop
// which runs the loop 60 to 30 times per second ,
// which vary according to browser.
function jumpcheck()
{
if(isjump)
{
ball.posy -=1; //make the character move 10 px based on fps..
window.timeoutHandle = window.setTimeout(function() {
isjump = false;
}, 1000);
}
}
}
注意:请求动画帧 FPS 介于 20 到 60 之间,始终在变化。
康斯坦丁所说的代码
var lastUpdate = Date.now();
function jumpcheck()
{
if(isjump)
{
speed = 1;
position = ball.posy;
var now = Date.now();
var dt = (now - lastUpdate) / 1000;
lastUpdate = now;
ball.posy = position + (speed * dt)
}
}
对于游戏,通常会将自最后一帧以来的时间包含在计算中。此时间通常称为 dt
delta-time。要计算您的新位置,您只需将经过的时间乘以当前速度即可获得新位置。在伪代码中,这看起来像这样:
speed = ...
position = ...
dt = ...
position = position + (speed * dt)