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

2013/1/22

Help? How to compare a world in an if statement?

Apple Apple

2013/1/22

#
I'm trying to make a mute button and since i have 2 worlds i have to put this in both of them, but i need help on the if statement that tell me which world.. im trying to use this code: if(Greenfoot.getWorld() = OpenMenu()), but it doesn't work? here's my code: import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) public class MuteButton extends Actor { //imports img private GreenfootImage image1 = new GreenfootImage("on.png"); private GreenfootImage image2 = new GreenfootImage("off.png"); //initiallizing variables private boolean soundOn; public MuteButton() { //when object is created, sets img to on button setImage(image1); soundOn = true; } /** * Act - do whatever the muteButton wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { checkClick (); // Add your action code here. } private void checkClick () { //get main menu world OpenMenu world = (OpenMenu) getWorld(); WaterWorld world2 = (WaterWorld) getWorld(); if(Greenfoot.getWorld() = OpenMenu()) { if (soundOn == true && Greenfoot.mouseClicked(this)) { world.stopMusic(); setImage(image2); soundOn = false; } else if ( soundOn == false && Greenfoot.mouseClicked(this)) { world.playMusic(); setImage(image1); soundOn = true; } } else if(Greenfoot.getWorld() == WaterWorld()) { if (soundOn == true && Greenfoot.mouseClicked(this)) { world2.stopMusic(); setImage(image2); soundOn = false; } else if ( soundOn == false && Greenfoot.mouseClicked(this)) { world2.playMusic(); setImage(image1); soundOn = true; } } } }
vonmeth vonmeth

2013/1/22

#
You need to use 'instanceof'. I can't think of another way to do it.
    private void checkClick ()
    {
        //get main menu world
	   World world = getWorld();

        if (soundOn == true && Greenfoot.mouseClicked(this))
        {
		 if(world instanceof OpenMenu)
			 ((OpenMenu) world).stopMusic();
		 if(world instanceof WaterWorld)
			 ((WaterWorld) world).stopMusic();

            setImage(image2);
            soundOn = false;
        }

        else  if ( soundOn == false && Greenfoot.mouseClicked(this))
        {
			if(world instanceof OpenMenu)
				((OpenMenu) world).playMusic();
			if(world instanceof WaterWorld)
				((WaterWorld) world).playMusic();
			
            setImage(image1);
            soundOn = true;
        }

    }
Oh, you could check mouseclick on the button inside your world as well, so you don't have to call the playMusic/stopMusic methods from the button.
You need to login to post a reply.