phaser 3 camera

Phaser 3 Make the camera follow the player

When I was building virtual worlds in Flash/As3 it took quite a bit of maths to make the background scroll. And then to scroll only when the avatar wasn’t near the edge of the world. Phaser’s built-in camera class makes this all very easy and quick.

This code continues to build on the code we build in the last several blog post and is using the utility template.

Set a background

While not totally necessary I like to set up a background to set the size of the camera. Otherwise, without a moving background. there is nothing to show that the player is moving.

 let bg = this.add.image(0, 0, "background").setOrigin(0, 0);
 Align.scaleToGameW(bg, 2);

Set the camera bounds

Now that we have the background in place, we can set the bounds of the main camera to the size of the background.

this.cameras.main.setBounds(0, 0, bg.displayWidth, bg.displayHeight);

Set the camera to follow

Now the last thing to do is to tell the camera to keep its focus on the player.


Leave a Comment