How to Create Interactive Sprites with Phaser 3 Adjusting CSS for Canvas Width

Adjusting CSS for Canvas Width

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:

css
canvas { width: 100%; }

Once the CSS is updated, refresh the page to confirm that the canvas now utilizes the full width of its container.


Adding Game Assets to the Scene

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.


Creating a Group

First, create a group to organize the assets:

javascript
this.items = this.add.group();

To add elements to the group, pass an array containing objects for each asset.

Example:

javascript
this.items.create({ key: 'building', setXY: { x: 100, y: 240 } });

Adding Multiple Elements

To include multiple elements (e.g., a house, car, and tree), you can repeat the process with additional objects:

javascript
this.items.create([ { key: 'building', setXY: { x: 100, y: 240 } }, { key: 'house', setXY: { x: 240, y: 280 }, setScale: { x: 0.8, y: 0.8 } }, { key: 'car', setXY: { x: 400, y: 300 } }, { key: 'tree', setXY: { x: 550, y: 250 } } ]);

Managing Element Depth

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:

javascript
background.setDepth(-1);

Setting Group Element Depth:
You can uniformly set the depth for all group items:

javascript
this.items.children.iterate(item => item.setDepth(1));

Making Elements Interactive

To make the background and group items interactive, we’ll enable interactivity and listen for pointer events.

Making the Background Interactive:

javascript
background.setInteractive(); background.on('pointerdown', pointer => { console.log('Background clicked', pointer); });

Making Group Items Interactive:
Use Phaser.Actions.Call to iterate over group elements and make them interactive:

javascript
Phaser.Actions.Call(this.items.getChildren(), item => { item.setInteractive(); item.on('pointerdown', () => { console.log(`You clicked ${item.texture.key}`); }); });

Future Enhancements

With this setup, we can add the following features to make the game more engaging:

  • Animations on Interaction: Highlight selected items using tween animations.
  • Hover Effects: Add visual or motion effects when hovering over items.
  • Custom Click Actions: Define unique behaviors for different items upon selection.

These enhancements will be covered in the next lesson.