问题描述
嗨,我正在尝试使用 javascript 和 phaser 3 库实现双跳,但它不起作用,我不知道为什么。我在 create() 中将 this.canDoubleJump 声明为 true,这是我的更新函数的代码.
const didPressJump = this.cursors.space.isDown;
if (didPressJump) {
if (this.player.body.onFloor()) {
this.canDoubleJump = true;
this.player.play('pablo_jump',true);
this.player.body.setVeLocityY(-200);
} else if (this.canDoubleJump) {
this.canDoubleJump = false;
this.player.body.setVeLocityY(-200);
}
}
编辑:
let justpressedJump = this.cursors.space.isDown;
if (!justpressedJump && this.player.body.onFloor()) {
this.player.allowedToJump = true;
}
if (justpressedJump && this.player.body.onFloor() && this.player.allowedToJump) {
this.canDoubleJump = true;
this.player.body.setVeLocityY(-200);
this.player.allowedToJump = false;
}
else if(this.canDoubleJump){
console.log(this.canDoubleJump)
this.player.body.setVeLocityY(-200);
this.canDoubleJump = false;
}
解决方案:
const didPressJump =Phaser.Input.Keyboard.JustDown(this.cursors.space);
if (didPressJump) {
if (this.player.body.onFloor()) {
this.canDoubleJump = true;
this.player.body.setVeLocityY(-200);
this.player.play('pablo_jump',true)
} else if (this.canDoubleJump) {
this.canDoubleJump = false;
this.player.body.setVeLocityY(-200);
this.player.play('pablo_double_jump',true)
}
}
解决方法
您的代码不起作用的原因:
- 用户按下空格键,例如0.3 秒
-
didPressJump
为真,this.player.body.onFloor()
为真。玩家跳跃 - 在一帧之后,例如1/30 = 0.0333 秒,
didPressJump
仍然为真,但this.player.body.onFloor()
为假。玩家在下一帧进行双跳。
解决方案:
双跳只能在用户释放空格键后触发。
还有另一个“错误”。当玩家正在下落 (!this.player.body.onFloor()
)) 但之前没有跳跃时,双跳是不可能的。但如果玩家跳跃、落地然后摔倒,则有可能进行二段跳。