[SOLVED] How to play sprite while two keys are being pressed?

I’ve made a 2D game, but a lot of people asked if I could make the walk cycle work when moving diagonally. Is there a way to be able to play a sprite animation while two keys are being pressed? My code as of the moment is as follows:

var GuardianMovement = pc.createScript('guardianMovement');

var mvspeed = 14;

GuardianMovement.prototype.initialize = function() {
    this.entity.collision.on('collisionstart', this.onCollisionStart, this);
    
};

GuardianMovement.prototype.update = function(dt) {
    
    
   if (this.app.keyboard.isPressed(pc.KEY_W)) {
    this.entity.sprite.play("walkingUp");  
       this.entity.rigidbody.applyForce(0,mvspeed,0);
   }
    
    
    if (this.app.keyboard.isPressed(pc.KEY_S)) {
    this.entity.sprite.play("walkingDown");
        this.entity.rigidbody.applyForce(0,-mvspeed,0);
   }
    
    if (this.app.keyboard.isPressed(pc.KEY_A)) {
    this.entity.sprite.play("walkingLeft");
        this.entity.rigidbody.applyForce(-mvspeed,0,0);
   }
    
    if (this.app.keyboard.isPressed(pc.KEY_D)) {
    this.entity.sprite.play("walkingRight");
        this.entity.rigidbody.applyForce(mvspeed,0,0);
   }
  
    if (this.app.keyboard.wasReleased(pc.KEY_S)) {
    this.entity.sprite.play("downidle");
   }
    
    if (this.app.keyboard.wasReleased(pc.KEY_W)) {
    this.entity.sprite.play("upidle");
   }
    
    if (this.app.keyboard.wasReleased(pc.KEY_A)) {
    this.entity.sprite.play("leftidle");
   }
    
    if (this.app.keyboard.wasReleased(pc.KEY_D)) {
    this.entity.sprite.play("rightidle");
   }
    
};

This is the code taught to us in class, so I don’t know any other way. Please help. Thank you!!

Hi @biskwit,

To check if both keys are being pressed in your update loop you could do something like this:

if (this.app.keyboard.isPressed(pc.KEY_W) && this.app.keyboard.isPressed(pc.KEY_A)) {
    this.entity.sprite.play("walkingUpLeft");  
       this.entity.rigidbody.applyForce(-mvspeed, mvspeed, 0);
   }

You will want to be careful with ordering your if() statements though. All of the conditionals that require two keys should be at the top of the if() tree and your single keypress if() statements should be converted to else if().

2 Likes

Similar thread: Diagonal Movement with Sprites

ohmygod it works finally!!!

I never thought of turning the other statements into else if statements.

i’m new to this so i dont know hahah

Thank you so much!!!

2 Likes