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

2018/3/24

Adding and removing object with the same button.

Recorsi Recorsi

2018/3/24

#
Hi, At the moment i can add an actor with the "1" key and remove it with "2".
if (Greenfoot.isKeyDown("1"))
        {
            addObject(screen, 450, 450);
        }
        if (Greenfoot.isKeyDown("2"))
        {
            removeObject(screen);
        }
I was wondering if i can open and close it with the same button, because with 2 it gets annoying fast. Is this possible and if so, how? Thanks
danpost danpost

2018/3/24

#
You could ask if the actor was in the world and then change that state, but then you have the problem that the key is detected for multiple act cycles and the end state would be pretty much be random each time. To avoid that, you will need a boolean to track the state of the key so you know when its state changes:
// field
private boolean oneDown;

// action
if (oneDown != Greenfoot.isKeyDown("1")) // did "1" key change states
{
    oneDown = ! oneDown; // save new state
    if (oneDown) // was "1" key pressed
    {
        // change state of screen
        if (screen.getWorld() == null) addObject(screen,450, 450);
        else removeObject(screen);
    }
}
Recorsi Recorsi

2018/3/24

#
That is the problem i had. Thank you :)
You need to login to post a reply.