This site requires JavaScript, please enable it in your browser!
Greenfoot back
BYY
BYY wrote ...

2024/12/11

isKeyDown

BYY BYY

2024/12/11

#
I am trying to make a code that add one to a variable if you click the space bar. The code I wrote made the variable keep increasing if i hold the space bar but I don't want it to do that
danpost danpost

2024/12/12

#
BYY wrote...
I am trying to make a code that add one to a variable if you click the space bar. The code I wrote made the variable keep increasing if i hold the space bar but I don't want it to do that
You could use the getKey method instead of isKeyDown. However, there are limitations on applying getKey for this use. Best is to add a boolean field to track the state of the "space" key:
private boolean spaceDown = false; // last "space" key state
private int variable = 0;  // the int field being increased

public void act() {
    if (spaceDown != Greenfoot.isKeyDown("space")) { // is there a change in state of the "space" key
        spaceDown = ! spaceDown;
        if (spaceDown) variable++; // if change is from up to down, increase value of variable
    }
}
Of course, you could instead have the variable increase when the key is released. Just NOT (!) the condition on line 7.
You need to login to post a reply.