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

2011/10/28

Different Actions, Different Worlds.

kiarocks kiarocks

2011/10/28

#
I am trying to make different things happen in different worlds. My current Code is:
public World whichworld;
    
    public Button(World world)
    {
        whichworld = world;
    }
    /**
     * Act - do whatever the Button wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        SpaceWorld.started = true;
        if(Greenfoot.mouseClicked(this) && whichworld == getWorld())
        {

            Greenfoot.setWorld(new CircutWorld());
        }
        else if(Greenfoot.mouseClicked(this) && whichworld == getWorld())

            Greenfoot.setWorld(new SpaceWorld());

        if(whichworld == getWorld())
        {
            GreenfootImage img = new GreenfootImage("Go to Work!",12,Color.black,Color.blue);
            setImage(img);
        }
        else if(whichworld == getWorld())
        {
            GreenfootImage img = new GreenfootImage("Back to Space!",12,Color.black,Color.green);
            setImage(img);
        }

    }    
this always fails once it switches. how do i make this work?
nccb nccb

2011/10/28

#
Your various conditions are testing the same thing. For example, this code:
if (whichworld == getWorld())
{
    ...
}
else if (whichworld == getWorld())
{
    ...
}
Will never execute the second branch. You're asking if the current world is "whichworld", and if that's not the case, you're asking if the current world is "whichworld" (which it definitely isn't). I think the easiest way to fix your code is to use instanceof:
if (getWorld() instanceof SpaceWorld)
{
    ...
}
else if (getWorld() instanceof CircutWorld)
{
    ...
}
And change the other if statement accordingly.
kiarocks kiarocks

2011/10/28

#
ahhh, thats what i wanted. Thanks!!
You need to login to post a reply.