我正在尝试用 Java 编写一个类似于马里奥的游戏,但在让这个家伙在奔跑时跳跃时遇到了问题。下面的代码最终做的是,当用户按住右键并按下跳跃按钮时,马里奥基本上停止奔跑和跳跃,所以就像用户放开了右键并按下了跳跃。
public void keyPressed(KeyEvent e) {
// here I keep track of what buttons the user pressed
int keyCode = e.getKeyCode();
if(keyCode == 37)
pressedKeys[0] = true;
else if(keyCode == 39)
pressedKeys[1] = true;
else if(keyCode == 68)
pressedKeys[2] = true;
// after I see what the user has pressed an action is carried out
Thread t = new Thread(this);
t.start();
}
public void performAction()
{
// depending on what the user has pressed a certain action is performed
if(pressedKeys[2]==true)
{
// changes the coordinates of the character itself
// done in another thread so the background can continue
// moving as the user holds down a direction
Thread t = new Thread(mcControl);
t.start();
}
if(pressedKeys[0]==true)
{
changeSprite();
bg.moveImageForward();
}
if(pressedKeys[1]==true)
{
changeSprite();
bg.moveImageBackward();
}
}
public void run() {
performAction();
}
最佳答案
if(keyCode == 37)
与您的问题无关,但切勿使用那样的代码。大多数人不知道这个神奇数字是什么意思。
更好的方法是使用:
if(keyCode == KeyEvent.VK_???)
现在您的代码是自文档化的。
关于java - 需要帮助在 java 中按下多个键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4118553/