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

2021/11/9

Return to a previous world

salim5112 salim5112

2021/11/9

#
Hello, i have 2 worlds, MyWorld and World_1. I also have 3 actors, Spieler, Glitz and Samen. if Spieler is touching Glitz, i want to switch to World_1. I did that by writing in the Spieler actor class: if (isTouching(Glitz.class)) { Greenfoot.setWorld(new World_1()); } and that worked, now after Samen reaches a location in World_1 I want to switch back to MyWorld What a wrote to do that in the Samen actor class: if (getX() == X && getY() == Y) { // X and Y certain locations in World_1 Greenfoot.setWorld(new MyWorld()); } this create a new MyWorld but I want to return to the previous world. Thanks.
danpost danpost

2021/11/9

#
The problem is that when you do:
Greenfoot.setWorld(new World_1());
in Spieler class, all references to the MyWorld object are lost. Two ways to prevent that are by: (1) passing a reference of the MyWorld object to the World_1 object; or (2) making a global variable and maintaining a reference to the MyWorld object there (in the MyWorld class). One (1) would involve using in Spieler class:
Greenfoot.setWorld(new World_1(getWorld()));
with the following in World_1 class:
public MyWorld myWorld;

public World_1(MyWorld mw)
{
    super(...);
    myWorld = mw;
    prepare();
}
and in Samen class:
Greenfoot.setWorld(((World_1)getWorld()).myWorld);
Two (2) is more simple. In MyWorld:
public static MyWorld myWorld;

public MyWorld()
{
    super(...);
    myWorld = this;
    prepare();
}
with the following in Samen class:
Greenfoot.setWorld(MyWorld.myWorld);
salim5112 salim5112

2021/11/12

#
it worked, thanks a lot ;)
You need to login to post a reply.