Thursday, June 7, 2018

java - 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.



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).


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...