-Sorry for the lengthty post
Hi I got source code from the Articles & tutorials section from the first post “Basic Game.” I implemented WASD control over a square that is being drawn on the screen but I’m having a small issue. If I’m moving right and click “A” without letting go of “D” I will eventually stop moving once I let go of “D” and then continue moving left again because I’m still holding down “A”.
private double x = 0;
private double y = 0;
private int velX, velY = 0;
private int movementSpeed = 4;
protected void update(int deltaTime) {
if (y > 700 - 30) { //Make sure square doesn't leave the screen
y = 700 - 30;
} else if (y < 0) {
y = 0;
} else {
y += velY;
}
if (x > 1000 - 30) { //Make sure square doesn't leave the screen
x = 1000 - 30;
} else if (x < 0) {
x = 0;
} else {
x += velX;
}
}
protected void render(Graphics2D g) {
g.fillRect((int) x, (int) y, 30, 30);
}
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_W) {
velY = -movementSpeed;
}
if (e.getKeyCode() == KeyEvent.VK_A) {
velX = -movementSpeed;
}
if (e.getKeyCode() == KeyEvent.VK_S) {
velY = movementSpeed;
}
if (e.getKeyCode() == KeyEvent.VK_D) {
velX = movementSpeed;
}
}
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_W) {
velY = 0;
}
if (e.getKeyCode() == KeyEvent.VK_A) {
velX = 0;
}
if (e.getKeyCode() == KeyEvent.VK_S) {
velY = 0;
}
if (e.getKeyCode() == KeyEvent.VK_D) {
velX = 0;
}
}
Thank you SO much for any help you can offer.