How do I implement a sprint ability in Phaser JS?

Viewed 102

I am trying to develop a dodge style game with falling enemies that features the ability for the player to 'sprint' while holding down the spacebar.

I have tried to multiply the velocity of the player while space.isdown() is true, but the player disappears once space is pressed.

function update() {
  if (gameState.cursors.left.isDown) {
    gameState.player.setVelocityX(-160);
  } else if (gameState.cursors.right.isDown) {
gameState.player.setVelocityX(160);
  } else {
gameState.player.setVelocityX(0);
  }
  //Sprint Ability
 if (gameState.player.velocityx != 0 && gameState.cursors.space.isDown){
  gameState.player.setVelocityX(gameState.player.velocityx * 2);
  } else {};
}
1 Answers

Your code is setting the players velocty to double the player's current velocity every time update is called, which is generally 60 times a second. So, the player's velocity is being doubled incredibly quickly, hence they disappear because they speed of the screen.

To avoid this, define a constant for the player's velocity, and set the velocity to double that constant.

Here is some code to achieve this, that I used in a game I made:

if(Game.controls.Run.isDown) {
    player.body.velocity.x = playerSpeed*2;
}

playerSpeed is the constant defining the players horizontal movement speed, in your case it appears to be 160.

You should be able to modify this for your code.

Related