Move the ball

This is the 4th step out of 16 of the Gamedev Phaser tutorial. We have our blue ball printed on screen, but it's doing nothing—it would be cool to make it move somehow. This article covers how to do just that.

Updating the ball's position on each frame

Remember the update() method and its definition? The code inside it is executed on every frame, so it's a perfect place to put the code that will update the ball's position on screen. Add the following new lines inside update(), as shown:

js
class ExampleScene extends Phaser.Scene {
  // ...
  update() {
    this.ball.x += 1;
    this.ball.y += 1;
  }
}

The code above adds 1 to the x and y properties representing the ball coordinates on the canvas, on each frame. Reload index.html and you should see the ball rolling across the screen.

Compare your code

Here's what you should have so far, running live. To view its source code, click the "Play" button.

Next steps

The next step is to add some basic collision detection, so our ball can bounce off the walls. This would take several lines of code—a significantly more complex step than we have seen so far, especially if we want to add paddle and brick collisions too—but fortunately, Phaser allows us to do this much more easily than if we wanted to use pure JavaScript.

In any case, before we do all that, we will first introduce Phaser's physics engines and do some setup work.