Animated character movement with W-A-S-D

Hello,

You can find all basics informations about animations here : Animations - Babylon.js Documentation

1. How do I get the animation played and moving the character only while key is pressed?

First, you have to listen to the keyboard events :

Example
let isZPressed = false;
let isQPressed = false;
let isSPressed = false;
let isDPressed = false;

document.addEventListener('keydown', (e) => {
    if (e.keyCode == 90) { isZPressed = true; }
    if (e.keyCode == 81) { isQPressed = true; }
    if (e.keyCode == 83) { isSPressed = true; }
    if (e.keyCode == 68) { isDPressed = true; }
    if (e.keyCode == 66) { isBPressed = true; }
});

document.addEventListener('keyup', (e) => {
    if (e.keyCode == 90) { isZPressed = false; }
    if (e.keyCode == 81) { isQPressed = false; }
    if (e.keyCode == 83) { isSPressed = false; }
    if (e.keyCode == 68) { isDPressed = false; }
});

Then in your game loop you have to check if the key is pressed.
If yes, you have to move your entity by multipling the its front vector (normal vector) with its speed.

Example (code maybe obsolete)

entity.moveWithCollisions(entity.frontVector.multiplyByFloats(entity.speed, entity.speed, entity.speed));

And this while playing your animation.

Simplified summary
if z is pressed {
    play the animation
    move the entity
} else {
    pause the animation
}

2. How do I get the character moving in the direction of the camera?

You need to set the player front vector in the same direction as the camera.

3. How do I get the run animation played, when w and shift are pressed at the same time?

Same as 1. but with the condition that shift + Z are pressed simultaneously and an other animation + speed

2 Likes