Stop animation when cursor key is released

I want the character to stop facing the current direction when the cursor key is released. Currently the character keeps playing the moving animation even when it comes to a stop.
My preload code:

const downconfig = {
            key: 'down',
            frames: this.anims.generateFrameNumbers('player',{start: 0, end: 3,}),
            frameRate: 5,
            repeat: -1
        };
        const upconfig = {
            key: 'up',
            frames: this.anims.generateFrameNumbers('player',{start: 34, end: 37,}),
            frameRate: 5,
            repeat: -1
        };
        const leftconfig = {
            key: 'left',
            frames: this.anims.generateFrameNames('player',{start: 51, end: 54}),
            frameRate: 5,
            repeat: -1
        };
        const rightconfig = {
            key: 'right',
            frames: this.anims.generateFrameNames('player',{start: 17, end: 20}),
            frameRate: 5,
            repeat: -1
        };
        const downidleconfig = {
            key: 'downidle',
            frames: [{key: 'player',frame:0}],
            frameRate: 20
        };
        const upidleconfig = {
            key: 'upidle',
            frames: [{key: 'player',frame:34}],
            frameRate: 20
        };
        const leftidleconfig = {
            key: 'leftidle',
            frames: [{key: 'player',frame:51}],
            frameRate: 20
        };
        const rightidleconfig = {
            key: 'rightidle',
            frames: [{key: 'player',frame:17}],
            frameRate: 20
        };
        this.anims.create(downconfig);
        this.anims.create(upconfig);
        this.anims.create(leftconfig);
        this.anims.create(rightconfig);
        this.anims.create(downidleconfig);
        this.anims.create(upidleconfig);
        this.anims.create(leftidleconfig);
        this.anims.create(rightidleconfig);

My update() code:

update(): void {
        this.player.setVelocity(0);        
        if(this.cursors.down.isDown){
            this.player.setVelocityY(80);
            this.player.anims.play('down',true);
        } else if(this.cursors.up.isDown){
            this.player.setVelocityY(-80);
            this.player.anims.play('up',true);
        }else if(this.cursors.left.isDown){
            this.player.setVelocityX(-80);
            this.player.anims.play('left',true);
        }else if(this.cursors.right.isDown){
            this.player.setVelocityX(80);
            this.player.anims.play('right',true);
        }
    }

previously I tried to play the idle animations by adding an else clause to each cursor key check but that did not work. How can I detect when the current cursor key is released?

One way is Phaser.Input.Keyboard.JustUp(key).

Another would be to check the current animation in a final else clause and play an idle animation if appropriate.

1 Like