A Phaser 3 example of controlling a sprite with mouse or keyboard
Phaser 3 Sprite Control Example

Before I really start on redoing my game in Phaser 3 (“phaser”: “3.18.1”) I decided I better learn it better by creating small examples. I also prefer nothing but Typescript and finding examples in Typescript can be tough.

While I really like the Phaser 3 Examples, I often find myself not fully understanding what does what without searching for details and browsing through the docs.

By creating and working with small examples I learn much faster than reading API docs.

Sprite Space Ship Scene Example

class SpriteSpaceShipScene extends Phaser.Scene {

    private cursors: Phaser.Types.Input.Keyboard.CursorKeys;
    private spaceship: Phaser.Physics.Arcade.Sprite;
    constructor() {
        super({
            key: 'SpriteSpaceShipScene'
        });
    }

    preload() {
        this.load.image('ship', 'assets/sh2.png');

    }
    create() {
        console.log('SpriteSpaceShip scene create');

        this.spaceship = this.physics.add.sprite(this.game.scale.parentSize.width / 2, this.game.scale.parentSize.height / 2, 'ship');
        this.spaceship.setDrag(35);//https://photonstorm.github.io/phaser3-docs/Phaser.Physics.Arcade.Components.Drag.html#setDrag
        let menuItem: Phaser.GameObjects.Text = this.add.text(15, 15, "Home", { fontFamily: 'Verdana, "Times New Roman", Tahoma, serif', fontSize: 22, color: '#0000ff' });
        menuItem.setInteractive().on('pointerdown', () => { this.scene.start('MenuScene'); });
        this.cursors = this.input.keyboard.createCursorKeys();
        this.spaceship.setCollideWorldBounds(true);
    }

    update() {
        
        let pointer: Phaser.Input.Pointer = this.input.activePointer; //https://photonstorm.github.io/phaser3-docs/Phaser.Input.Pointer.html
        let velocity: Phaser.Math.Vector2 = new Phaser.Math.Vector2();//https://photonstorm.github.io/phaser3-docs/Phaser.Math.Vector2.html
        if (pointer.isDown) {
            let angleTo: number = Phaser.Math.Angle.BetweenPoints(this.spaceship, pointer);//https://photonstorm.github.io/phaser3-docs/Phaser.Math.Angle.html#.BetweenPoints__anchor
            this.physics.velocityFromRotation(angleTo, 150, velocity);//https://photonstorm.github.io/phaser3-docs/Phaser.Physics.Arcade.ArcadePhysics.html#velocityFromRotation__anchor
            this.spaceship.setVelocity(velocity.x, velocity.y);//https://photonstorm.github.io/phaser3-docs/Phaser.Physics.Arcade.Components.Velocity.html#setVelocity__anchor
            this.spaceship.rotation = angleTo;
        }
        if (this.cursors.left.isDown) {
            this.spaceship.angle -= 1;
        }
        if (this.cursors.right.isDown) {
            this.spaceship.angle += 1
        }
        if (this.cursors.up.isDown) {
            this.physics.velocityFromRotation(this.spaceship.rotation, 150, velocity);
            this.spaceship.setVelocity(velocity.x, velocity.y);
        }
        if (this.cursors.down.isDown){
            this.spaceship.setVelocity(0);
        }
    }
}

export default SpriteSpaceShipScene

Phaser-3-documented-examples full project on GitHub. Live Demo: Phaser 3 Examples

Since the main functionality of my Phaser 2 game is moving a space ship around this seemed like a good place to start.

This small example allows control with keyboard arrows or mouse.

In a final check of the demo before publishing it I did find one problem.

If you have a touchscreen lap top you can use that to control the sprite. Returning to use the mouse and it no longer works.

I will look more into this to see if I am doing something wrong or if it is a bug. It seems that this.input.activePointer should be correct.

This also does not seem to go away if you return to the main menu and a full page refresh is needed to get back mouse control.

In my main config I have debug set to true to show a box around the sprite and directional indicator.

import 'phaser';
import MenuScene from './scenes/MenuScene';
import SpriteSpaceShipScene from './scenes/SpriteSpaceShipScene';
const config: Phaser.Types.Core.GameConfig = {
  type: Phaser.AUTO,
  parent: 'content',
  width: window.innerWidth,
  height: window.innerHeight,
  resolution: 1,
  scale: {
    mode: Phaser.Scale.RESIZE,
    autoCenter: Phaser.Scale.CENTER_BOTH
  },
  physics: {
    default: 'arcade',
    arcade: {
      debug: true
    }
  },
  backgroundColor: "#000000",
  scene: [MenuScene, SpriteSpaceShipScene]
};

let game: Phaser.Game = new Phaser.Game(config);

The Menu Scene which is a work in progress as I plan on adding many more examples for this.

class MenuScene extends Phaser.Scene {
    private menuItems: Phaser.GameObjects.Text[];
    constructor() {
        super({
            key: 'MenuScene'
        }); 
    } 

    preload() {
        
    }
    create() {
        console.log('menu scene create');
        this.menuItems = new Array<Phaser.GameObjects.Text>();
        let center = this.game.scale.parentSize.width/2-275; //https://photonstorm.github.io/phaser3-docs/Phaser.Scale.ScaleManager.html#parentSize__anchor
        this.add.text(center,25,"Phaser Examples",{ fontFamily: 'Verdana, "Times New Roman", Tahoma, serif', fontSize: 64, color: '#ffffff' });
        let menuItem:Phaser.GameObjects.Text = this.add.text(center,100,"Sprite movement control (mouse / keyboard)",{ fontFamily: 'Verdana, "Times New Roman", Tahoma, serif', fontSize: 32, color: '#ffffff' });
        //https://photonstorm.github.io/phaser3-docs/Phaser.Types.Input.html#.InteractiveObject
        menuItem.setInteractive().on('pointerdown',()=>{ this.scene.start('SpriteSpaceShipScene');});
        //mouse - touch events https://rexrainbow.github.io/phaser3-rex-notes/docs/site/touchevents/
        menuItem.on('pointerover',() => {this.menuItems[0].setTint(0x0000FF)});
        menuItem.on('pointerout',() => {this.menuItems[0].clearTint()});
        this.menuItems.push(menuItem);
    }
}

export default MenuScene

My goal is to add as many examples as I can and contain enough documentation links or comments to assist with learning Phaser 3.

My next example will probably continue on this scene by adding a background image and interaction with other sprites.

The space ship used in this example from Open Game Art

Leave a comment

Your email address will not be published. Required fields are marked *