Diagonal Movement with Sprites

Hello, I’ve been having a dilemma with movement animations as I’ve been using a code like this

if (this.app.keyboard.isPressed(pc.KEY_W)) {
this.entity.sprite.play(“DemonUp”);
this.entity.rigidbody.applyForce(0.0,movementSpeed,0.0);
}

For every other key (W, A, S, D) I would use that code but with a different sprite animation. I also made one for idle animations:

if (this.app.keyboard.wasReleased(pc.KEY_W)) {
    this.entity.sprite.play("DemonUpIdle");
}

However, I don’t know what code to use to play a diagonal animation; as of yet, when I hold the keys W, and D, the sprite animation is stuck on one frame that it was previously on. Is there a way I can code pressing W and D at the same time to play a specific sprite animation? Thank you for any help if ever :slight_smile:

At the moment, the code switching between the two different animations of the W and D keys in the same frame which means it will always gets stuck on the first frame of whichever animation is played last in the update frame.

Rather than each key having it’s own logic, the input as a whole should have a single output.

eg

var moving = false;
var direction = new pc.Vec3();

if (this.app.keyboard.isPressed(pc.KEY_W)) {
    direction.y = 1;
    moving = true;
}

if (this.app.keyboard.isPressed(pc.KEY_D)) {
    direction.x = 1;
    moving = true;
}

if (moving) {
    if (direction.x > 0) {
        this.entity.sprite.play("DemonLeft");
    } else {
        this.entity.sprite.play("DemonRight");
    }

    if (direction.y > 0) {
        this.entity.sprite.play("DemonUp");
    } else {
        this.entity.sprite.play("DemonDown");
    }
} else {
    this.entity.sprite.play("DemonUpIdle");
}
1 Like

Thank you for your input! Will try this out