用于Keyboard.getEventKeyState
确定当前事件,然后Keyboard.getEventKey
确定这是哪个键。然后,您需要确保通过 禁用重复事件Keyboard.enableRepeatEvents
。保持当前运动的状态,根据这些事件进行更改,并且每个刻度都会相应地移动。如下所示,作为速写:
Keyboard.enableRepeatEvents(false);
...
/* in your game update routine */
final int key = Keyboard.getEventKey();
final boolean pressed = Keyboard.getEventKeyState();
final Direction dir = Direction.of(key);
if (pressed) {
movement = dir;
} else if (movement != Direction.NONE && movement == dir) {
movement = Direction.NONE;
}
...
/* later on, use movement to determine which direction to move */
在上面的例子中,Direction.of
为按下的键返回适当的方向,
enum Direction {
NONE, LEFT, RIGHT, DOWN, UP;
static Direction of(final int key) {
switch (key) {
case Keyboard.KEY_A:
return Direction.LEFT;
case Keyboard.KEY_D:
return Direction.RIGHT;
case Keyboard.KEY_W:
return Direction.UP;
case Keyboard.KEY_S:
return Direction.DOWN;
default:
return Direction.NONE;
}
}
}