Javascript 如何在update()上使用x坐标来增加精灵的速度?
非常初学者,可能是愚蠢的问题。我正在跟随一个关于PhaserJs的教程,我需要逐渐增加我在键盘上移动的精灵的速度 我试着设置一个自动增量,但它似乎不能正常工作 这是我到目前为止用同样的速度在x上移动精灵的方法Javascript 如何在update()上使用x坐标来增加精灵的速度?,javascript,phaser-framework,Javascript,Phaser Framework,非常初学者,可能是愚蠢的问题。我正在跟随一个关于PhaserJs的教程,我需要逐渐增加我在键盘上移动的精灵的速度 我试着设置一个自动增量,但它似乎不能正常工作 这是我到目前为止用同样的速度在x上移动精灵的方法 function create() { gameState.codey = this.add.sprite(150, 200, 'codey') // Set cursor keys here! gameState.cursors = this.input.keyboard.c
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
}
有了这个代码,精灵以相同的速度移动,击中右箭头。但是如果我想让它逐渐加速呢?
我曾经尝试过“``gameState.codey.x=x++”,但实际上没有起作用
感谢您的帮助,对于这个超级愚蠢的问题,我深表歉意。Phaser有一个内置的物理系统,可以大大简化您的工作。更新游戏配置,以包含如下属性:
var config = {
...
physics: {
default: 'arcade'
},
...
};
gameState.codey = this.physics.add.sprite(150, 200, 'codey');
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**物理引擎。它可以为您处理速度和加速度之类的事情,这样您就不会在按下按钮时手动增加速度
一旦你加入了物理引擎,你就可以更新你的精灵,让它像这样被物理控制:
var config = {
...
physics: {
default: 'arcade'
},
...
};
gameState.codey = this.physics.add.sprite(150, 200, 'codey');
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);
}
}
如果您只想在按下按钮时移动播放机,则在声明播放机后需要添加以下内容:
gameState.codey.setVelocity(0, 0);
然后,为了处理播放机的递增速度,您需要更新update()
,如下所示:
var config = {
...
physics: {
default: 'arcade'
},
...
};
gameState.codey = this.physics.add.sprite(150, 200, 'codey');
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物理引擎为您的精灵提供的更多方法和属性
**请注意:Phaser提供多种物理引擎——Arcade只是一种选择。您可以看到其他选项正在运行