Reputation: 498
How can I implement diagonal movement to a sprite? I created a movable sprite (a rectangle), which moves in four directions.
To animate the rectangle, a timer object and action performed method was used. I implemented the following code in keyPressed and keyReleased method to move it in four directions.
public void keyPressed(KeyEvent arg0){
int c=arg0.getKeyCode();
if(c==KeyEvent.VK_LEFT){
velx=-4;
vely=0;
}
else if(c==KeyEvent.VK_RIGHT){
velx=4;
vely=0;
}
else if(c==KeyEvent.VK_UP){
velx=0;
vely=-4;
}
else if(c==KeyEvent.VK_DOWN){
velx=0;
vely=4;
}
}
public void keyReleased(KeyEvent arg0){
velx=0;
vely=0;
}
Upvotes: 0
Views: 2515
Reputation: 46841
Here is code based on your last comments:
// Set of currently pressed keys
private final Set<Integer> pressed = new TreeSet<Integer>();
@Override
public void keyPressed(KeyEvent arg0) {
int c = arg0.getKeyCode();
pressed.add(c);
if (pressed.size() > 1) {
Integer[] array = pressed.toArray(new Integer[] {});
if (array[0] == KeyEvent.VK_LEFT && array[1] == KeyEvent.VK_UP) {
velx = -4;
vely = -4;
} else if (array[0] == KeyEvent.VK_UP && array[1] == KeyEvent.VK_RIGHT) {
velx = 4;
vely = 4;
} else if (array[0] == KeyEvent.VK_RIGHT && array[1] == KeyEvent.VK_DOWN) {
velx = 4;
vely = -4;
} else if (array[0] == KeyEvent.VK_LEFT && array[1] == KeyEvent.VK_DOWN) {
velx = -4;
vely = 4;
}
} else {
if (c == KeyEvent.VK_LEFT) {
velx = -4;
vely = 0;
} else if (c == KeyEvent.VK_RIGHT) {
velx = 4;
vely = 0;
} else if (c == KeyEvent.VK_UP) {
velx = 0;
vely = -4;
} else if (c == KeyEvent.VK_DOWN) {
velx = 0;
vely = 4;
}
}
}
@Override
public void keyReleased(KeyEvent arg0) {
velx = 0;
vely = 0;
pressed.remove(Integer.valueOf(arg0.getKeyCode()));
}
Upvotes: 0
Reputation: 324108
Don't use a KeyListener. Swing was designed to be used with Key Bindings
.
Check out Motion Using the Keyboard for more information and a complete solution that uses Key Bindings
.
Upvotes: 2