我遇到了一个关于控制降落伞运动的自动收报机的有趣问题。每当加速度方向改变时,它需要 60 毫秒才能生效,这会导致一些奇怪的行为,例如降落伞撞到游戏墙上并在它交换方向之前“磨擦”。
当它撞到墙上时,在这个测试用例中它应该立即改变方向。这似乎是偏移循环导致的,但是我在没有循环的情况下运行了基本代码,它仍然以相同的方式运行。
基础引擎是 Phaser 3,tick() 直接在它的 Update() 循环中运行。
我已经使用 setInterval 和 requestAnimationFrame 直接对此进行了测试 - 它们会产生相同的奇怪延迟。
tick(time)
{
if (this.last == 0)
{
this.last = time;
}
let offSet = Math.min(time - this.last, 5000);
let dragMod = (1 - this.drag);
for(let i = 0; i < offSet; i++);
{
if (!this.isGrounded)
{
if (this.AccelDirection == -1)
{
this.XSpeed += -this.windPower;
}
if (this.AccelDirection == 0)
{
this.XSpeed = 0;
}
if (this.AccelDirection == 1)
{
this.XSpeed += this.windPower;
}
this.YSpeed += this.gravity;
this.X += this.XSpeed;
this.Y += this.YSpeed;
this.YSpeed *= dragMod;
this.XSpeed *= dragMod;
if (this.X >= 868)
{
this.X = 868; // Right //
if (this.isMe)
{
this.AccelDirection = -this.AccelDirection;
//this.scene.bounce();
}
}
if (this.X <= 32)
{
this.X = 32; // Left //
if (this.isMe)
{
this.AccelDirection = -this.AccelDirection;
//this.scene.bounce();
}
}
} else {
this.YSpeed = 0;
this.XSpeed = 0;
}
if (this.Y > 868)
{
this.isGrounded = true;
}
}
this.x = this.X;
this.y = this.Y;
this.last = time;
}
我用 console.log 观察了这个循环,它在遇到条件的那一秒就识别出它,通常在它改变之前最多计算 59 毫秒。
最佳答案
不确定这是否能解决问题,但您可以完全摆脱循环:
tick(time)
{
if (!this.last) {
// cannot compute offset without a "last" property
this.last = time;
return;
}
let offSet = Math.min(time - this.last, 5000);
let dragMod = (1 - this.drag);
let ySpeed = this.gravity;
let xSpeed = this.AccelDirection < 0 ? -this.windPower :
this.AccelDireciton < 1 ? 0 :
/* otherwise */ this.windPower;
this.isGrounded = this.Y > 868;
if (!this.isGrounded) {
this.XSpeed += xSpeed * offSet;
this.YSpeed += ySpeed * offSet;
this.X += this.XSpeed;
this.Y += this.YSpeed;
this.XSpeed *= dragMod;
this.YSpeed *= dragMod;
if (this.isMe) {
if (this.X >= 868 || this.X <= 32) {
this.X = this.X >= 868 ? 868 : 32;
this.AccelDirection *= -1;
// this.scene.bounce();
}
}
} else {
this.XSpeed = this.YSpeed = 0;
}
this.x = this.X;
this.y = this.Y;
this.last = time;
}
关于javascript - 为什么变量更改要延迟 x 毫秒才能生效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55537584/