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

2016/11/4

how can i remove an object when i click on something from another world

hockeydude1155 hockeydude1155

2016/11/4

#
so far this is all i have done for the code the Hero2 class has an image in another world of where the mouseClicked is being called
1
2
3
4
5
6
7
8
public void act()
{
    if (Greenfoot.mouseClicked(this))
    {
        Greenfoot.setWorld(new City());
        getWorld().removeObject(Hero2());
    }
}
danpost danpost

2016/11/4

#
If you want to remove the Hero2 object from the new City world, you will need a reference to that world; and you will need a reference to the Hero2 object in that world:
1
2
3
City city = new City();
Greenfoot.setWorld(city);
city.removeObjects(city.getObjects(Hero2.class));
By the way, your 'getWorld' method call on line 6 still returns the world where the click occurred. The line is equivalent to:
1
this.getWorld().removeObject(< Hero2 object reference >);
where 'this' is the actor in the "then" active world that caused the act method to execute.
danpost danpost

2016/11/4

#
If you had the Hero2 object reference in an instance field and a method to return that Hero2 object in the City class:
1
2
3
4
5
6
private Hero2 hero2 = new Hero2();
 
public Hero2 getHero()
{
    return hero2;
}
then you could remove it specifically with:
1
2
3
City city = new City();
Greenfoot.setWorld(city);
city.removeObject(city.getHero());
You need to login to post a reply.