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

2011/12/10

Greenfoot.isKeyDown() problem/bug

henrikland henrikland

2011/12/10

#
Hi I'm making a game using Greenfoot as a school project, and have run into a problem with the isKeyDown()-method. The game has an intro in which images are shown, and then the player should press "enter" to continue. This is accomplished with:
public void waitForEnter() {
    Greenfoot.delay(1);     //need this to allow things on the stack to execute before entering the loop
    while (true) {
        if (Greenfoot.isKeyDown("enter")) {
            break;
        }
    }
}
The problem is that if you press enter a bunch of times, the next time waitForEnter() is called, it breaks out of the loop immediately. Even though isKeyDown() is supposed to return true only if the key is CURRENTLY pressed down, it seems to remember previous presses. It even remembers key-presses when changing worlds using setWorld(), as after the intro a new World starts where pressing enter has a certain effect, and if you press enter during the end of the intro, Greenfoot registers that enter is pressed down as soon as the new world starts. Is this a known issue or am I doing something wrong?
kiarocks kiarocks

2011/12/10

#
i think it has to do with a backup of keys. It still thinks the key is pressed down.
danpost danpost

2011/12/10

#
Instead of checking if the key is down, just send the keystroke to a variable and check it for 'enter'.
String myKey = "";
while (!("enter".equals(myKey))) myKey = Greenfoot.getKey();
You can put the following code in before it to clear the buffer:
while(Greenfoot.getKey() != null);
danpost danpost

2011/12/10

#
Basically, if you want a certain action to repeat while a key is pressed, you would want to use 'isKeyDown(String key)'. But if you are just needing a particular keystroke (or one of several), you would want to use 'getKey()'.
davmac davmac

2011/12/12

#
You need to login to post a reply.