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

2011/9/16

Changing a Background

rvevea rvevea

2011/9/16

#
So I've been racking my brain trying to figure out how to do this and/or why the hell this won't work. I basically want to, upon the act loop running, change the background from one background to another. I figured something like this would work: public void switchBG() { World world1 = getWorld(); Greenfootimage bg1 = new GreenfootImage("blah.jpg"); Greenfootimage bg2 = new GreenfootImage("blah2.jpg"); if (world1.getBackground() == bg1) { world1.setBackground(bg2); } else { world1.setBackground(bg1); } } Any tips? I'm probably missing something completely obvious so apologies for my terrible coding skills. Thanks! RV
bourne bourne

2011/9/16

#
I'd imagine that when you set the background to a new Image, the reference you passed it is lost so you can't compare the reference you gave it to creating a new reference (with the "=="). Though they may be the same image. Basically try not to compare images to what an object may have as an image. Try creating a separate variable that knows what background was last given to display. So maybe have a boolean that is true if "blah.jpg" was the last image given to the background. And when you call this switchBG method, if it's true: setBackground to "blah2.jpg", if false: setBackground to "blah.jpg". AND change the boolean to not equal it self (bool = !bool) Hope that makes sense and is helpful
rvevea rvevea

2011/9/16

#
Extremely helpful! Thank you! just for reference: Created a global boolean
public boolean lastbg = true;
then had the if statements check the boolean value like so:
if (lastbg == true) {
            world1.setBackground(bgImage_2);
            lastbg = false;
            
        }
        else 
        {
            world1.setBackground(bgImage_1);
            lastbg = true;
        }
You need to login to post a reply.