我将它用于一个简单的 2.5D 游戏,但我的按键似乎没有切换。在主类中调用它不是问题,因为将 println 语句放在 if 语句中没有运行。提前谢谢。
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);
}
}
}