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

2016/3/27

Trouble with booleans

grog2 grog2

2016/3/27

#
I want to make a boolean which toggles true or false when you click the object but i cant get it to work
private boolean selected = false;
   
    public void act() 
    {
        if (selected == false && Greenfoot.mouseClicked(this))
        {
            selected = false;
        }
        if (selected == true && Greenfoot.mouseClicked(this))
        {
            selected = false;
        }
        
        if (selected == true)
        {
            getImage().setTransparency(50);
        }
    }  
I think i might be using the wrong operators or something but this doesn't work and I don't understand why.
danpost danpost

2016/3/27

#
I do not see any code that sets the value of 'selected' back to 'true'; nor anything the resets the transparency of the image back to 255. You can toggle the boolean 'selected' with this line:
selected = !selected;
Then you need to only ask about the click:
if (Greenfoot.mouseClicked(this))
{
    selected = !selected;
}
Then you only need to change the transparency when the value is changed:
if (Greenfoot.mouseClicked(this))
{
    selected = !selected;
    if (selected)
    {
        getImage().setTransparency(50);
    }
    else
    {
        getImage().setTransparency(255);
    }
}
grog2 grog2

2016/3/28

#
Thanks, but the transparency doesn't seem to return to 255 when I click the object again - if I click it once it goes to 50, but then if I keep clicking it, nothing happens.
grog2 grog2

2016/3/28

#
Never mind, I think something was wrong with greenfoot not compiling or something, I restarted it and it works fine now. Thanks!
You need to login to post a reply.