Before updating our JavaScript code, let’s first ensure the game canvas fits 100% of the available screen width. This CSS adjustment ensures the game is fully visible, even on smaller screens.
To do this, add the following CSS rule:
Once the CSS is updated, refresh the page to confirm that the canvas now utilizes the full width of its container.
To enhance the scene, we’ll incorporate various assets like buildings, cars, houses, and trees. These assets are stored in the assets/images
folder. Instead of creating individual sprites for each asset, we’ll use a group. Groups allow us to manage multiple game elements collectively.
First, create a group to organize the assets:
To add elements to the group, pass an array containing objects for each asset.
Example:
To include multiple elements (e.g., a house, car, and tree), you can repeat the process with additional objects:
In Phaser, elements are rendered in the order they are added, but their depth (z-index) can be customized for more control over the rendering hierarchy.
Setting Background Depth:
Setting Group Element Depth:
You can uniformly set the depth for all group items:
To make the background and group items interactive, we’ll enable interactivity and listen for pointer events.
Making the Background Interactive:
Making Group Items Interactive:
Use Phaser.Actions.Call
to iterate over group elements and make them interactive:
With this setup, we can add the following features to make the game more engaging:
These enhancements will be covered in the next lesson.