简体   繁体   中英

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. 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. Is there a way to tell the keyEvent or keyPressed to update on whats happening at the moment and react to it?

Here's the fragment of the code... ps I'm new to stack overflow and not a fluent java programmer I'm still learning. 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*/

Fix attempt#1 :
I tried using a return statement after a change was made hoping that would work, no result...

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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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