Skip to content Skip to sidebar Skip to footer

Character Stops After Second Key Pressed Is Lifted

I'm taking input from the arrow keys and moving a character accordingly on a 2D canvas game in JavaScript. When I press two keys, I want special things to happen like moving diagon

Solution 1:

To move diagonal, you need an x component, not just a Y. So you need a listener for both x and y.

Also, for this, why not just do (instead of forcing the client to do the calculations for no reason):

if(Keys.up && Keys.down){
    return;
}

Also, when you add the X component, dont use "else if" - just use "if" as you want to be able to capture more than one input at a time to move diagonally.

Should look something like:

if(Keys.up && Keys.down){
    return;
}
if(Keys.down){
    character.y += 10;
}
if(Keys.up){
    character.y -= 10;
}
if(Keys.left){
    character.x -= 10;
}
if(Keys.right){
    character.x += 10;
}

You can also do interpolation using CSS animation to move between the positions in order to make the movement smoother (and not jump 10px each button press).


Post a Comment for "Character Stops After Second Key Pressed Is Lifted"