I have 2 objects in my JFrame windows, I want them to follow my keys(arrows or buttons ASDW) as arrows control one object and ASDW control the other one, my problem is the objects are not flawless, they move in the direction I press but if I press 'D' (it starts moving right) and then I press 'W' it will not start moving up, it can control only one key press at a time.
Here is my code:
addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_DOWN)
vely2 = 1;
else if (e.getKeyCode() == KeyEvent.VK_UP)
vely2 = -1;
else if (e.getKeyCode() == KeyEvent.VK_LEFT)
velx2 = -1;
else if (e.getKeyCode() == KeyEvent.VK_RIGHT)
velx2 = 1;
else if (e.getKeyCode() == KeyEvent.VK_S)
vely1 = 1;
else if (e.getKeyCode() == KeyEvent.VK_W)
vely1 = -1;
else if (e.getKeyCode() == KeyEvent.VK_A)
velx1 = -1;
else if (e.getKeyCode() == KeyEvent.VK_D)
velx1 = 1;
b1.setLocation(b1.getLocation().x + 5 * velx1, b1.getLocation().y + 5 * vely1);
b2.setLocation(b2.getLocation().x + 5 * velx2, b2.getLocation().y + 5 * vely2);
}
@Override
public void keyReleased(KeyEvent arg0) {
vely2 = 0;
vely1 = 0;
velx1 = 0;
velx2 = 0;
}
@Override
public void keyTyped(KeyEvent arg0) {
}
});
How can I make it move like in this example. Thanks :)