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

2024/9/22

Setting location after switching worlds

NeedyJellyfish NeedyJellyfish

2024/9/22

#
Hi, im trying to set the location of my test character called test(), after switching worlds. I do this by letting the test character touch the HappyPortal() class to switch to the happy world and i use the StartPortal() class to twitch back to the starting world called MyWorld. I tried using the setLocation(); command, but somehow the test object is at the start location after switching back to starting world from the happy world. Can someone help me with this???
public void switching(){
        if (isTouching(HappyPortal.class)){
            Greenfoot.setWorld(new NewWorld2());
            }
        if (isTouching(StartPortal.class)) {
            Greenfoot.setWorld(new MyWorld());
            setLocation(100, 200);
        }
    }   
Super_Hippo Super_Hippo

2024/9/22

#
The “setLocation” method is still executed on the actor in its current world. The actor isn’t somehow automatically transferred into the new world.
NeedyJellyfish NeedyJellyfish

2024/9/23

#
Do you know how to fix it?
danpost danpost

2024/9/23

#
NeedyJellyfish wrote...
Do you know how to fix it?
If there are no attributes that need to be passed along with the actor, then simply have a new actor of that type added to the new world by way of its constructor, as usual. Otherwise, best is to transfer the actor to the next world. This is most easily done by adding a secondary constructor to the initial world that accepts an actor of the type 'test':
public MyWorld() {
    this(new test()); // transfers execution to the following constructor
)

public MyWorld(test character) {
    super(600, 400, 1);
    // normal constructor codes  -- with
    addObject(character, 100, 200);
}
In the NewWorld2 class, you will not need the first constructor, only the second one. You will then be able to use the following in the test class:
Greenfoot.setWorld(new NewWorld(this));
to transfer to the new world. And, similarly for going back..
NeedyJellyfish NeedyJellyfish

2024/9/25

#
It worked!!!!! Thank you soooooo much
You need to login to post a reply.