Click here to Skip to main content
15,891,204 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi, i have a little problem because I want to my rectangle on jumping only one times when i click space, but not repeat when i holding this key

What I have tried:

Java
@Override
public void keyPressed(KeyEvent e) {

    if(e.getKeyCode() == KeyEvent.VK_SPACE) {
        jump();
    }
}

public void jump() {

    if(started) {

        if (yMotion > 0) {
            yMotion = 0;
        }
        yMotion -= 20;
    }
}
Posted
Updated 17-Jan-20 21:42pm
v3

1 solution

Why not use keyReleased[^]

Another option would be to use both keyPressed and keyReleased and if you have already jumped after the key has been pressed, you wouldn't jump again. In pseudo code, something like
@Override
    public void keyPressed(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_SPACE && jumpOk) {
            jump();
            jumpOk=false;
        }
    }
....
<pre>@Override
    public void keyReleased(KeyEvent e) {
       jumpOk=true;
    }


Just remember to initialize the jumpOk variable to true when you start this part of the program
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900