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

2014/6/13

Add a delay after pressing a button?

7788 7788

2014/6/13

#
public class Display extends Actor
{
    public void act() 
    {
        if (Greenfoot.isKeyDown("space"))
          
        

        setImage(new GreenfootImage("" + Greenfoot.getRandomNumber (90), 32, Color.BLACK, Color.WHITE));
    } 
}    
I have this code to make a Random Number Generator. When I press space it generates about 5 numbers at the same time, this isn't what I want to do. I'd like to press space then for the program to generate one number when the button is pressed, I will need to press the button multiple times.
danpost danpost

2014/6/13

#
Instead of the 'isKeyDown' method, maybe you should use the 'getKey' method. The 'isKeyDown' method will return true as long as the key is down; the 'getKey' method will return null unless a key is released, when it will return a String representation of which key was released. If no other code in your project requires individual keystrokes like this, then change line 5 to:
if ("space".equals(Greenfoot.getKey())
If there are other places in your project that do require individual keystrokes, then you will need to add an instance boolean field to track the state of the "space" key:
// with instance field
private boolean spaceDown;
// and code
if (!spaceDown && Greenfoot.isKeyDown("space"))
{
    spaceDown = true;
    // set image
}
if (spaceDown && !Greenfoot.isKeyDown("space")) spaceDown = false;
CooliMC CooliMC

2014/6/13

#
Use this: public class Display extends Actor { Boolean return=true; public void act() { if (Greenfoot.isKeyDown("space")&&return=true) Return=false; setImage(new GreenfootImage("" + Greenfoot.getRandomNumber (90), 32, Color.BLACK, Color.WHITE)); } if(Greenfoot.isKeyDown("Space")==false&&return==false) { return=true; } }
CooliMC CooliMC

2014/6/13

#
or you did it like danpost said :D
You need to login to post a reply.