I'm using this for a simple 2.5D game but my keys don't seem to toggle. It isn't a problem while calling it in the main class as placing println statements in the if statements didn't run. Thanks ahead of time.
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class InputHandler implements KeyListener {
public InputHandler(Game game) {
game.addKeyListener(this);
}
public class Key {
private boolean pressed = false;
private int numTimesPressed = 0;
public boolean isPressed() {
return pressed;
}
public int getnumTimesPressed() {
return numTimesPressed;
}
public void toggle(boolean isPressed) {
pressed = isPressed;
if (isPressed()) {
numTimesPressed++;
}
}
}
// *This is where your keys go.
public Key up = new Key();
public Key down = new Key();
public Key left = new Key();
public Key right = new Key();
public void keyPressed(KeyEvent e) {
toggleKey(e.getKeyCode(), true);
}
public void keyReleased(KeyEvent e) {
toggleKey(e.getKeyCode(), false);
}
public void keyTyped(KeyEvent e) {
}
public void toggleKey(int keyCode, boolean isPressed) {
if (keyCode == KeyEvent.VK_W) {
up.toggle(isPressed);
}
if (keyCode == KeyEvent.VK_S) {
down.toggle(isPressed);
}
if (keyCode == KeyEvent.VK_A) {
left.toggle(isPressed);
}
if (keyCode == KeyEvent.VK_D) {
right.toggle(isPressed);
}
}
}