java - 需要帮助在 java 中按下多个键

标签 java

我正在尝试用 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/

相关文章:

java - Akka 用于异步处理?

java - Ant 无法找到 javac 编译器

java - 有谁知道我为什么会收到此 IllegalMonitorStateException?

java - Itext GifImage 第一个输入流未关闭

java - 修改方法中的枚举参数值

java - 从资源中获取位图

java - 没有任何改变,但出现 "peer not authenticated"错误

java - 如何在 JavaFX 中展开和折叠 TitledPane

java - 自定义 JPanel 在第二个自定义 JPanel 中导致呈现问题

java - Hibernate 多对多关系