How do I move a custom sprite with arrow keys?

Hi, I’m learning to use phaser and now I have to move a custom sprite with arrow keys. I’ve followed all the steps of this tutorial but it doesn’t explain how to resolve that particular issue.

The simplest one, you may use this function inside create() method to define the keys you wanted to be registered:
this.keys = this.input.keyboard.addKeys('LEFT,RIGHT,UP,DOWN,Z,X');
ref: https://labs.phaser.io/edit.html?src=src\input\keyboard\add%20key%20using%20string.js

And can be access by this in update() method:
this.keys.LEFT.isDown or
this.keys.LEFT.isUp

This input example: https://labs.phaser.io/index.html?dir=input/keyboard/&q=

While the moving sprite can be achieve either by position (ex: sprite.x -= 1) or velocity (ex: sprite.setVelocity(-5, 0))

3 Likes

Thanks for your answer. On the other hand, the biggest problem I have to solve is when I try to switch between frames of sprite sheet.

Its simply to call sprite.setFrame(frame: number | string); isn’t?
But I dont know, most of spritesheet work with it.
And also you need to register the animation first from the same key texture that used.

Cmiiw if I don’t get the problem xD

I can assure you that I am not an expert xD. However, after many attempts, I have got the following functions:

      preload() {
          this.load.multiatlas('wssjblue', 'assets/character/wssjblue.json', 'assets/character');
      }
      
      create() {
          this.anims.create({
             key: 'left',
             frames: [{key: 'wssjblue', frame: '001.png'}],
             frameRate: 10,
             repeat: -1
         }); 
         this.anims.create({
            key: 'right',
            frames: [{key: 'wssjblue', frame: '003.png'}],
            frameRate: 10,
            repeat: -1
        }); 
         this.anims.create({
            key: 'idle',
            frames: [{key: 'wssjblue', frame: '002.png'}],
            frameRate: 10,
        });
        this.cursors = this.input.keyboard.addKeys('LEFT,RIGHT');
        }
    }
    update() {
        if (this.cursors.LEFT.isDown) {  
            this.player.body.setVelocityX(-160);
            this.player.anims.play('left', true);
        else if (this.cursors.RIGHT.isDown) {
            this.player.body.setVelocityX(160);
            this.player.anims.play('right', true);
        }
        else {
            this.player.body.setVelocityX(0);
            this.player.anims.play('idle', true);
        }
    }

That works, but I dont know how to use the function: this.anims.generateFrameNames