Controlling sprite speed

In the update calls, we have been incrementing the position of the ship sprite by 2. In real life, however, you may want to store that value as a global constant or a centralized setting. In this case, changing the overall speed means that we need to update a single constant or variable, instead of refactoring the whole game.

We have already moved the screen size into constants; let's do the same with the speed:

  1. Introduce a new constant called shipSpeed and set its value to 2:
      const screenWidth = 800;
const screenHeight = 600;
const shipSpeed = 2;
  1. Now, update all of the existing code and use the shipSpeed constant in all of the places you need to increment or decrement the position of the ship, as shown in the following code:
      function update() {
// RIGHT button
if (cursors.right.isDown) {
ship.x += shipSpeed;
if (ship.x >= screenWidth) {
ship.x = 0;
}
ship.flipX = false;
}
// LEFT button
else if (cursors.left.isDown) {
ship.x -= shipSpeed;
if (ship.x <= 0) {
ship.x = screenWidth;
}
ship.flipX = true;
}
// UP button
else if (cursors.up.isDown) {
ship.y -= shipSpeed;
if (ship.y <= 0) {
ship.y = screenHeight;
}
}
// DOWN button
else if (cursors.down.isDown) {
ship.y += shipSpeed;
if (ship.y >= screenHeight) {
ship.y = 0;
}
}
}

As you can see, you now have a single place that holds the speed of the ship. Any changes that are made to the shipSpeed constant will be reflected in all of the code blocks since we're not refactoring the code in multiple places. 

  1. Now, change the speed to 4 and see what happens:
      const shipSpeed = 4;

Notice how the ship is now two times faster than before when it moves in all four directions. You can experiment more and either increase or decrease the speed of the ship until you find a value that provides the best and smooth movement behavior.

It is good practice to use constants or variables to control various aspects of the game in a single place. This helps us to avoid code duplication and the need for refactoring.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.90.141