Home > Enterprise >  If else statement not playing animation with multiple keys in Phaser
If else statement not playing animation with multiple keys in Phaser

Time:10-16

I am trying to make my character run when the user holds shift while walking with the right arrow key, however for some reason when I hold shift while pressing the right arrow key the run animation is not played. The animation works properly if I add it for the shift key only but when I add the logic for the right arrow key it doesn't work. Any idea why and how can I detect both keys successfully? Here is my statement:

 function handlePlayerControls() {
    
    if (cursors.left.isDown)
    {
        player.setVelocityX(-160);
    
        player.anims.play('walkLeft', true);
    }
    else if (cursors.right.isDown)
    {
        player.setVelocityX(160);
    
        player.anims.play('walkRight', true)
        
    } else if (cursors.shift.isDown && cursors.right.isDown) {
        player.anims.play('runRight', true)
    }
    else
    {
        player.setVelocityX(0);
    
        player.anims.play('idle', true);
    }
    
    if (cursors.up.isDown && player.body.blocked.down)
    {   
         
        player.setVelocityY(-330);
    }
    
 }

CodePudding user response:

This happens because the code block for if(cursors.right.isDown) gets run before the code block for if(cursors.shift.isDown && cursors.right.isDown)

In order to fix this, you can move the code block for the shift above the cursors.right

function handlePlayerControls() {
    if (cursors.left.isDown) {
        player.setVelocityX(-160);
        player.anims.play('walkLeft', true);
    } else if (cursors.shift.isDown && cursors.right.isDown) {
        player.anims.play('runRight', true)
    } else if (cursors.right.isDown) {
        player.setVelocityX(160);
        player.anims.play('walkRight', true)
    } else {
        player.setVelocityX(0);
        player.anims.play('idle', true);
    }
    if (cursors.up.isDown && player.body.blocked.down) {
        player.setVelocityY(-330);
    }
}

Personally, I would extract the function into a new function called walk, here is what it would look like after the change.

/**
 * Move the player to the given direction
 * @param shouldRun {boolean} - If the player should run
 * @param direction {string} - The direction to move the player
 */
const walk = (shouldRun = false, direction = 'Left') => {
    const animation = shouldRun ? 'run' : 'walk'
    player.setVelocityX(direction === 'Left' ? -160 : 160)
    player.anims.play(`${animation}${direction}`, true)
}

function handlePlayerControls() {
    if (cursors.left.isDown) {
        walk(cursors.shift.isDown, 'Left')
    } else if (cursors.right.isDown) {
        walk(cursors.shift.isDown, 'Right')
    } else {
        player.setVelocityX(0);
        player.anims.play('idle', true);
    }
    if (cursors.up.isDown && player.body.blocked.down) {
        player.setVelocityY(-330);
    }
}
  • Related