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

2021/4/2

How can I get the active world in the actor class?

Leon137 Leon137

2021/4/2

#
I created new Levels in my game and now the actor needs to know in which world he is, in order to use a method of the active world. I have three worlds, which have almost the same code besides the spawn rate of the actor and the background image. If i play the game with my initially world, everything works fine, but if I choose the "easy" or "hard" world, the game crashes because i'm referring to a method from the initially world and not the active one.
public void click()
    {
        if (Greenfoot.mouseClicked(this)){
            Counter counter = ((Welt //needs to be the active World)getWorld()).getCounter();
            if (speed >= 8){
                counter.heraufzaehlen(+2);
            }else{
                counter.heraufzaehlen(+1);
            }
            switch(Greenfoot.getRandomNumber(3)){
                case 0: Greenfoot.playSound("chick_hit1.mp3"); break;
                case 1: Greenfoot.playSound("chick_hit2.mp3"); break;
                case 2: Greenfoot.playSound("chick_hit3.mp3"); break;
            }
            getWorld().addObject(new Vogel_Explosion(), getX(), getY());
            getWorld().removeObject(this);
        }
    }
public Welt()
    {    
        super(720, 400, 1);
        setBackground ("Hintergrund.png");

        counter = new Counter();
        addObject(counter, 160, 18);

        showText("Your Score:", 60, 15);

        prepare();
        
        addObject(timerDisplay, 360, 30);
    }

    public Counter getCounter()
    {
        return counter;
    }
public EasyWelt()
    {    
        super(720, 400, 1);
        setBackground ("EasyBackground.png");

        counter = new Counter();
        addObject(counter, 160, 18);

        showText("Your Score:", 60, 15);

        prepare();
        
        addObject(timerDisplay, 360, 30);
    }

    public Counter getCounter()
    {
        return counter;
    }
Gbasire Gbasire

2021/4/2

#
use this : (replace MyWorld with the world you want)
if(this.getWorld().getClass() == MyWorld.class)
{
    //your code
}
RcCookie RcCookie

2021/4/2

#
World w = getWorld();
Leon137 Leon137

2021/4/2

#
Gbasire wrote...
use this : (replace MyWorld with the world you want)
if(this.getWorld().getClass() == MyWorld.class)
{
    //your code
}
Works for me, thanks a lot for your help :)
danpost danpost

2021/4/2

#
There is also:
if (getWorld() instanceof MyWorld)
You need to login to post a reply.