Your First PhaserJS Game

Character Controls

Learn to add keyboard controls in PhaserJS to move and animate your game character with ease.

In the last chapter, we learned how to make our game world gravity-licious with some solid physics and collision detection! 🛠 Now it's time to help our character break free from standing still—he’s been stuck for too long! He’s probably thinking, "Hey, I've been standing here forever! Do something before I collapse!" So let's give him some controls before he faints from boredom! 😴

PhaserJS makes it super easy to handle keyboard events. We’ll use the built-in keyboard controls feature to move our character left, right, and make him jump around! 🏃‍♂️💨

Adding Keyboard Controls 🕹️

To get started, add the following line inside the create() function in your mainScene.js file:

this.cursors = this.input.keyboard.createCursorKeys();

What’s happening here? 🧠

This magical line creates an object this.cursors, which gives you access to the arrow keys: up ⬆️, down ⬇️, left ⬅️, and right ➡️. With these, we can detect when the player is pressing any of those keys! 🎉

Moving the Character 🏃‍♂️

Now, let’s get the character moving! Add the following code inside the update() function:

update() {
    if (this.cursors.left.isDown) {
        this.player.setVelocityX(-200); // Move left
        this.player.flipX = true; // Flip sprite to face left
 
        if (this.player.body.touching.down) {
            this.player.anims.play("player_run_anim", true); // Run animation
        }
    } else if (this.cursors.right.isDown) {
        this.player.setVelocityX(200); // Move right
        this.player.flipX = false; // Face right
 
        if (this.player.body.touching.down) {
            this.player.anims.play("player_run_anim", true); // Run animation
        }
    } else {
        this.player.setVelocityX(0); // Stop moving
 
        if (this.player.body.touching.down) {
            this.player.anims.play("player_idle_anim", true); // Idle animation
        }
    }
 
    if (this.cursors.up.isDown && this.player.body.touching.down) {
        this.player.setVelocityY(-370); // Jump
 
        this.player.anims.play("player_jump_anim", true); // Jump animation
    }
}

12

Breaking it Down 🧩

  1. Left and Right Movement:

    • When the left arrow key is pressed, this.cursors.left.isDown becomes true. We set the character’s horizontal velocity to -200 to move left. Similarly, pressing the right arrow key sets the velocity to 200 for moving right.
    • We also flip the character's sprite (flipX = true or false) to make him face the correct direction. 🔄
    • If the player is on the ground (this.player.body.touching.down), we trigger the running animation. 🏃‍♂️
  2. Stopping the Character:

    • If neither the left nor right key is pressed, the velocity is set to 0 so the player doesn’t keep moving. We also switch back to the idle animation if the player is still on the ground. 🛑
  3. Jumping:

    • When the up arrow key is pressed and the player is on the ground, we set the vertical velocity to -370, making the character jump. 🚀
    • While jumping, we switch to the jump animation. 🦘

You Did It! 🎉

Whoa, you did it! Your character now runs left and right, and even jumps like a pro. 🎮 Adding controls wasn’t that hard, right? Now you can run around your game world and have some fun. 🏃‍♂️💥

In the next chapter, we’ll spice things up by adding apple collection 🍎 and other fun features! Stay tuned for more adventure!


Complete Code 📜

If you missed anything or made some accidental changes, here’s the complete code for reference! 💻🔧


import Phaser from "phaser";
 
export default class LoadingScene extends Phaser.Scene {
    constructor() {
        super({
            key: "LoadingScene"
        });
    }
    preload() {
        // background
        this.load.image("bg", "assets/bg.png")
 
        // ground
        this.load.image("ground", "assets/ground.png")
 
        // spike
        this.load.image("spike", "assets/spike.png")
 
        // items
        this.load.spritesheet("apple", "assets/Items/Apple.png", {
            frameWidth: 32,
            frameHeight: 32
        })
        this.load.spritesheet("collected", "assets/Items/Collected.png", {
            frameWidth: 32,
            frameHeight: 32
        })
 
        // main character
        this.load.spritesheet("player_idle", "assets/character/idle.png", {
            frameWidth: 32,
            frameHeight: 32
        })
        this.load.spritesheet("player_hit", "assets/character/hit.png", {
            frameWidth: 32,
            frameHeight: 32
        })
        this.load.spritesheet("player_jump", "assets/character/jump.png", {
            frameWidth: 32,
            frameHeight: 32
        })
        this.load.spritesheet("player_run", "assets/character/run.png", {
            frameWidth: 32,
            frameHeight: 32
        })
 
        // platforms
        this.load.image("platform_brown", "assets/Platforms/Brown.png")
        this.load.image("platform_grey", "assets/Platforms/Grey.png")
 
        // falling platforms
        this.load.image("falling_platform_off", "assets/FallingPlatforms/Off.png")
        this.load.spritesheet("falling_platform_on", "assets/FallingPlatforms/On.png", {
            frameWidth: 32,
            frameHeight: 10
        })
 
        // Trampoline
        this.load.image("trampoline_idle", "assets/Trampoline/Idle.png")
        this.load.spritesheet("trampoline_jump", "assets/Trampoline/Jump.png", {
            frameWidth: 28,
            frameHeight: 28
        })
    }
    create() {
        // main character animations
        this.anims.create({
            key: "player_idle_anim",
            frames: this.anims.generateFrameNumbers("player_idle", {
                start: 0,
                end: 10
            }),
            frameRate: 20,
            repeat: -1
        })
        this.anims.create({
            key: "player_hit_anim",
            frames: this.anims.generateFrameNumbers("player_hit", {
                start: 0,
                end: 6
            }),
            frameRate: 12,
        })
        this.anims.create({
            key: "player_jump_anim",
            frames: this.anims.generateFrameNumbers("player_jump", {
                start: 0,
                end: 0
            })
        })
        this.anims.create({
            key: "player_run_anim",
            frames: this.anims.generateFrameNumbers("player_run", {
                start: 0,
                end: 11
            }),
            frameRate: 20,
            repeat: -1
        })
 
        // falling platform on
        this.anims.create({
            key: "falling_platform_on_anim",
            frames: this.anims.generateFrameNumbers("falling_platform_on", {
                start: 0,
                end: 3
            }),
            frameRate: 12,
            repeat: -1
        })
 
        // apple animation
        this.anims.create({
            key: "apple_anim",
            frames: this.anims.generateFrameNumbers("apple", {
                start: 0,
                end: 16
            }),
            frameRate: 20,
            repeat: -1
        })
 
        // Trampoline Jump Animation
        this.anims.create({
            key: "trampoline_jump_anim",
            frames: this.anims.generateFrameNumbers("trampoline_jump", {
                start: 0,
                end: 7
            }),
            frameRate: 20,
            repeat: 0
        })
 
        this.scene.start("MainScene");
    }
    update() {
 
    }
}

Now you have everything! 🚀 Enjoy creating your awesome PhaserJS game!

On this page