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

2016/1/2

buttons query

davemib123 davemib123

2016/1/2

#
Hi, I have got two buttons, one to restart:
 private void restartGame()
    {
        if (Greenfoot.mousePressed(this) || Greenfoot.isKeyDown("enter") || Greenfoot.isKeyDown("space"))
        {
            Greenfoot.setWorld(new StartScreen());
        }
    }
thats in gameoverObjects.class and one to start:
private void startGame()
    {
        if (Greenfoot.mousePressed(this) || Greenfoot.isKeyDown("enter") || Greenfoot.isKeyDown("space"))
        {
            Greenfoot.setWorld(new Level());
        }
    }
that's in startScreenObjects.class The problem that I have is that if I hold the "enter" or "space" key when on the gameover screen it will start the level world with only a small glimpse of the startscreen. How do I prevent this from happening?
Super_Hippo Super_Hippo

2016/1/2

#
You could have a variable like 'buttonPressed'.
private boolean buttonPressed = true;

public void act()
{
    if (buttonPressed && !Greenfoot.isKeyDown("enter") && !Greenfoot.isKeyDown("space")) buttonPressed = false;
    if (!buttonPressed) restartGame(); //or startGame(); for the other button
}
danpost danpost

2016/1/2

#
Instead of using 'isKeyDown', which is a method that will return true for as long as the key is down, use 'getKey', which returns once, when a key is released. Since you are checking for two different keys, you will need to save the returned value in a variable and check for each one individually ('getKey' will not return the same instance of a released key more than once).
davemib123 davemib123

2016/1/3

#
this is what i've tried - not sure if i've done it correctly though. the same issue persists that when I hold down enter or space it still continues through:
private void startGame()
    {
        
         if (Greenfoot.mousePressed(this) || "space".equals(Greenfoot.getKey()) || "enter".equals(Greenfoot.getKey()) && buttonPressed)
        {
            buttonPressed = true;
            Greenfoot.setWorld(new Level());
        }
        if (buttonPressed && !"space".equals(Greenfoot.getKey()) || !"enter".equals(Greenfoot.getKey())) buttonPressed = false;
     
    }
Super_Hippo Super_Hippo

2016/1/3

#
You are not using my act method, right? Ok, with danpost's advice, add this line in line 3:
String key = Greenfoot.getKey();
and change all instances of 'Greenfoot.getKey()' to 'key' and report back if anything changed.
danpost danpost

2016/1/3

#
You should also be using 'mouseClicked' in place of 'mousePressed' (you should not need the 'buttonPressed' field at all).
You need to login to post a reply.