我正在用 Java 制作游戏,并且正在研究玩家移动,但是每当按下方向键时,玩家就会移动,但在我释放键时不会停止。
我似乎看不出我做错了什么。有人可以指出我正确的方向吗?
// 输入类实现 KeyListener
public static final int LEFT = 0;
public static final int RIGHT = 1;
public static final int UP = 2;
public static final int DOWN = 3;
public boolean[] keys = new boolean[64];
public void getKeys(KeyEvent e, boolean move) {
switch(e.getKeyCode()) {
case KeyEvent.VK_LEFT:
keys[LEFT] = move;
break;
case KeyEvent.VK_RIGHT:
keys[RIGHT] = move;
break;
case KeyEvent.VK_UP:
keys[UP] = move;
break;
case KeyEvent.VK_DOWN:
keys[DOWN] = move;
break;
case KeyEvent.VK_BACK_QUOTE:
keys[BQUOTE] = move;
break;
}
keys[OTHER] = move;
}
@Override
public void keyPressed(KeyEvent e) {
getKeys(e, true);
}
@Override
public void keyReleased(KeyEvent e) {
getKeys(e, false);
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
// 播放器类
public void tick() {
if (Engine.key_input.keys[KInput.LEFT]) {
dx = -speed;
animDir = SpriteLoader.L;
sprite = SpriteLoader.anim(SpriteLoader.ANIM_PLAYER, animDir);
}
if (Engine.key_input.keys[KInput.RIGHT]){
dx = speed;
animDir = SpriteLoader.R;
sprite = SpriteLoader.anim(SpriteLoader.ANIM_PLAYER, animDir);
}
if (Engine.key_input.keys[KInput.UP]){
dy = -speed;
animDir = SpriteLoader.U;
sprite = SpriteLoader.anim(SpriteLoader.ANIM_PLAYER, animDir);
}
if (Engine.key_input.keys[KInput.DOWN]){
dy = speed;
animDir = SpriteLoader.D;
sprite = SpriteLoader.anim(SpriteLoader.ANIM_PLAYER, animDir);
}
}
// 引擎类
public class Engine {
public Input key_input;
public Engine() {
key_input = new Input();
}
// add keyListener(Input) to component
}