gpt4 book ai didi

javascript - 如何使用 update() 上的 x 坐标来增加 Sprite 的速度?

转载 作者:行者123 更新时间:2023-11-28 03:35:29 25 4
gpt4 key购买 nike

非常初学者,可能是愚蠢的问题。我正在遵循有关 PhaserJs 的教程,并且我需要逐渐增加按下键盘时移动的 Sprite 的速度。

我尝试设置自动增量,但似乎无法正常工作。

这是迄今为止我以相同的速度在 x 上移动 Sprite 的方法。

function create() {
gameState.codey = this.add.sprite(150, 200, 'codey')
// Set cursor keys here!
gameState.cursors = this.input.keyboard.createCursorKeys();

}

function update() {
// Update based on keypress here!
let speed= 5;
if(gameState.cursors.right.isDown) {
gameState.codey.x+=5
}

使用该代码, Sprite 会以与向右箭头相同的速度移动。但如果我想让它逐渐加速怎么办?我尝试过执行“`` gameState.codey.x = x++”,但实际上并没有起作用。

感谢您的帮助,并对这个 super 愚蠢的问题表示歉意。

最佳答案

Phaser 有一个内置的物理系统,可以大大简化您想要做的事情。更新您的游戏配置以包含 physicals 属性,如下所示:

var config = { 
...
physics: {
default: 'arcade'
},
...
};

这使您可以访问 Arcade** 物理引擎 API Doc 。它会为您处理速度和加速度等事情,因此您无需在按下按钮时手动增加速度。

合并物理引擎后,您可以将 Sprite 更新为物理控制,如下所示:

gameState.codey = this.physics.add.sprite(150, 200, 'codey');

如果您只希望玩家在按下按钮时移动,则需要在声明玩家后添加以下内容:

gameState.codey.setVelocity(0, 0);

然后,为了处理播放器的增量速度,您需要将 update() 更新为如下所示:

function update() {
...
if(gameState.cursors.right.isDown) {
gameState.codey.setVelocityX(5).setAccelerationX(5);
} else { // no buttons pressed
gameState.codey.setVelocity(0, 0).setAcceleration(0, 0);
}
}

您可以查看 Arcade 物理引擎为您的 Sprite 提供的更多方法和属性 here .

**请注意:Phaser 提供多种物理引擎 - Arcade 只是其中一种选择。您可以看到其他正在运行的选项 here .

关于javascript - 如何使用 update() 上的 x 坐标来增加 Sprite 的速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57785892/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com