Reputation: 29
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 diagonally and stopping.
These special things do happen, however there is a glitch when I lift up the second key that was pressed down: my character stops moving. This doesn't happen, though, if I lift the first key pressed and keep the second key pressed. In that case, my character continues in that direction. Why does this occur??
Here is a snippet of the function:
//both up and down keys pressed, character should stop
if(Keys.up && Keys.down){
character.y -= 10;
character.y += 10;
}
else if(Keys.down){
character.y += 10;
}
else if(Keys.up){
character.y -= 10;
}
Also, I am taking the input from onkeydown
and onkeyup
events and storing them in an object called Keys. (e.g. Keys[e.keyCode] = true )
When the key is pressed, that key's boolean value is true. When lifted it is false.
Upvotes: 1
Views: 303
Reputation: 3478
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).
Upvotes: 0