简体   繁体   English

如何在Java的KeyEvent中更新当前的keyPressed?

[英]How do I update the current keyPressed in a KeyEvent for java?

I would be extremely grateful if some one could help me with my code, I'm learning code as I develop games. 如果有人可以帮助我编写代码,我将非常感激,我在开发游戏时正在学习代码。

  • I'm trying to make the controls on a basic PONG game feel smooth, but I have this problem with the keyEvent/keyPressed. 我正在尝试使基本PONG游戏上的控件感觉平滑,但是keyEvent / keyPressed出现了此问题。 I am using A to go left, D to go right, when I hold D then press A, without letting go of D it will notice the change and go left, but once i let go of A with D still held down, the keyEvent will not notice that D is held down, which makes the racquet not move until you press D again. 我使用A向左走,D向右走,当我按住D然后按A时,不放开D就会注意到更改并向左走,但是一旦我放开A并仍然按住D放开,keyEvent不会注意到D处于按下状态,这使得球拍不会移动,直到您再次按D为止。 Is there a way to tell the keyEvent or keyPressed to update on whats happening at the moment and react to it? 有没有办法告诉keyEvent或keyPressed更新当前发生的事情并对之做出反应?

Here's the fragment of the code... ps I'm new to stack overflow and not a fluent java programmer I'm still learning. 这是代码的片段... ps我是堆栈溢出的新手,而不是我仍在学习的熟练的Java程序员。 I'm sorry if my question is very vague or unspecific... also, move(1) makes coordinates of the racquet move x+=1 and move(-1) x-=1*/ 很抱歉,如果我的问题很模糊或不确定,... move(1)使球拍的坐标移动x + = 1和move(-1)x- = 1 * /

Fix attempt#1 : 修复尝试#1:
I tried using a return statement after a change was made hoping that would work, no result... 进行更改后,我尝试使用return语句,希望它能奏效,但是没有结果...

public void keyPressed(KeyEvent e) {
    //MOVE LEFT
    if (e.getKeyCode() == KeyEvent.VK_A){               
        if(e.getKeyCode() == KeyEvent.VK_D){
            move(1);
            //maybe update?
            return;
        }                           
        else
            move(-1);           
    }       
    //MOVE RIGHT
    if (e.getKeyCode() == KeyEvent.VK_D){                   
        if(e.getKeyCode() == KeyEvent.VK_A) {
            move(-1);
            //maybe update?
            return;
        }
        else
            move(1);
    }               
}

The best way to handle this situation is to create a boolean array and store the values of everything in there and then use it later. 处理这种情况的最佳方法是创建一个布尔数组并将所有值存储在其中,然后在以后使用。 This allows for updates to be handled a bit more smoothly and allows for you to have a bit more of organization. 这样可以使更新的处理更加顺畅,并让您有更多的组织空间。 To create the array at the top type 在顶部类型创建数组

public static boolean[] keys = new boolean[999];

Then in the press method do 然后在新闻方法中

public void keyPressed(KeyEvent e) {
    keys[e.getKeyCode()] = true;
}

And finally in the release method 最后是释放方法

public void keyReleased(KeyEvent e) {
    keys[e.getKeyCode()] = false;
}

Then to reference it later simply use 然后稍后引用即可使用

[class].keys[KeyEvent.[key]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM