Are you building your first game as a Developer to showcase your Javascript skills with Phaser 3? Well, I was in the same position during my training at Microverse. I had to do a platform game as a final project in the Javascript module. I was a bit concerned but excited at the same time in the beginning, because, let’s face it! As a newbie, I wouldn’t think of building a game to show my skills and what I have learned so far. I had a lot of fun building my game and I put my best to build it the way I wanted to be and make it look like a pro in a short time.
First of all, I want to explain what a camera is in Phaser. A camera is a view of the game world, which bounds are set to be the same as the dimensions for your game given in config. It becomes important for the game world to be larger than what a player sees upon entering the game, to grant the joy of exploration and discovery. After some tutorials and discussions that I found on the internet, I had still got stuck on how to set the bounds when using a camera in my game. The goal was to make my sprite collide with the sides left, right, and up of the bounds, but not the bottom side because I wanted it to fall from the platforms. In this way, the player would lose the game, and the game over scene would appear on the player’s screen.
To do that, in the code below, first I modified the default camera (this.cameras.main), to make it aware that the world is larger than our current window. In my platform game, I set the first two arguments with a value of 0, which are the x and y position of the camera, relative to the top-left of the game canvas. The next two arguments are the width and the height of the camera, in pixels. Do the same for the physics of the game world. Furthermore, the camera follows along with your sprite by calling .startFollow(), its first argument is the sprite you want to follow. Next, you pass the roundPixels value, which is a boolean that affects rendering, it helps to keep the game away from camera jitter when you set it to true. The last two arguments are lerpX and lerpY parameters, those are the speed (between 0 and 1, defaults to 1) with which the camera locks on to the sprite. A lower lerp speed will have the effect that your character is moving much faster than the camera.
Finally, you pass a boolean value as an argument for each side of the camera’s bounds (left, right, up, and bottom). Also, do the same for the game’s world physics. Set any side to true if you want a bound or false if you don’t, I set the bottom side to false to add a losing condition when my sprite falls from the platforms. Then, you set the .setCollideWorldBounds() to true to enable the body of the sprite to collide with the world bounds of all its sides as well.
In the end, it was necessary and important to enable the world’s bounds as true only in the sides I wanted as I’ve shown you above. Now, your platform game is going to rock!