# Preventing diagonal movement

I was originally fine with diagonal movement but it's clashing with my sprite animation...

    public void keyPressed(KeyEvent e){
int key = e.getKeyCode();

switch(key){
case KeyEvent.VK_W:{
dir = 3;
velY = -speed;
break;
}
case KeyEvent.VK_S:{
dir = 2;
velY = speed;
break;
}
case KeyEvent.VK_A:{
dir = 1;
velX = -speed;
break;
}
case KeyEvent.VK_D:{
dir  = 0;
velX = speed;
break;
}
}
}

public void keyReleased(KeyEvent e){
int key = e.getKeyCode();

switch(key){
case KeyEvent.VK_W:{
velY = 0;
break;
}
case KeyEvent.VK_S:{
velY = 0;
break;
}
case KeyEvent.VK_A:{
velX = 0;
break;
}
case KeyEvent.VK_D:{
velX = 0;
break;
}
}
}

public void update(){
y += velY;
x += velX;
}


I thought that perhaps a switch statement or an if else statement would prevent multiple keys from firing at once, but it's not working out. I even tried synchronizing some methods but still to no avail. Any suggestions? And please ignore the dir variable I use it to find the direction the player is facing.

• If you press A then velX gets set to non-zero, and then if you press S after that without letting go of A, velY gets set to non-zero, so you get diagonal movement. If you want to stop moving in Y when someone presses A or D, then you need to set velY to 0 when you set velX to non-0, and vice versa – amitp Jul 12 '14 at 17:16

## 1 Answer

Obtaining multiple key presses can be found in this answer: How do I handle multiple key presses in Java?

Assign each one to a boolean variable and then check each key and add to the movement vector. Opposite keys will cancel out, and you can also test whether a key is already in use based on that.

if(noDiagonal)
{
velX = 0;
velY = 0;

if(keyLeft) velX += -1;
if(keyRight) velX += 1;

if(velX == 0)
{
if(keyUp) velY += -1;
if(keyDown) velY += 1;
}
}
else // In case you change your mind...
{
velX = 0;
velY = 0;

if(keyLeft) velX += -1;
if(keyRight) velX += 1;
if(keyUp) velY += -1;
if(keyDown) velY += 1;

// Normalize to prevent high speed diagonals
float length = sqrt((velX * velX ) + (velY * velY ));
velX = velX/length;
velY = velY/length;
}
velX *= speed;
velY *= speed;


Pick which animation/direction to use based on the speed in that direction, rather than the key. This will make it easier to handle automatic animation later (like in a cutscene), or you can turn that part off individually (like if they're standing on a conveyer belt).

• Thank you for this much more dynamic and versatile way of handling movement and forgive me for such a late reply! – r0llingthund3r Jul 13 '14 at 10:09