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

2013/2/24

vanishing objects.

i need to make an object vanish at the edge of the world. does anyone know the code?
danpost danpost

2013/2/24

#
The World class has a 'removeObject' method that you can use to remove an object from the world. To get a reference to the world from within an sub-class of Actor, use the 'getWorld' method of the Actor class. Make sure that you do not execute any code requiring the actor be in the world after removing it. Use of the 'return' statement and the condition 'if (getWorld() != null)' can be used to avoid doing so.
please elaborate and simplify. i'm a newbie
Jonas234 Jonas234

2013/2/25

#
you can get the object of the current World with getWorld() now you can get the height and width with: getWorld().getHeight(); and getWorld().getWidth() ; Now you can compare this Values to the actual Position of your Actor (getX(), getY()) and if the gap is small enough you can just call the getWorld().removeObject(this) function. But if you want to execute other Methods in the removed Object then you get nullPointerExceptions. So you need to be sure that no other functions will be called afterwards. Jonas
i'm still confused
Jonas234 Jonas234

2013/2/26

#
int gapX = 10;
int gapY =8;
if (getX() >= getWorld().getWidth()-gapX || getX() <= gapX || getY() >= getWorld().getHeight()-gapY || getY() <= gapY)
{
getWorld().removeObject(this)
}
gapX and gapY is just to get an area where you touch the edge. In the if condition you are testing if your object is next to the edge of the World. If one of the 4 conditions is true it will execute getWorld().removeObject(this). So it will remove the current Object. The Problem is, if you want to execute other Methods in this Object after you removed it from the World, you will get an Error. So you need to make sure that no over Method will be called. You can do this by adding an boolean like isRemoved oder sth like that or by removing the Object at the End of the add Cycle.
thank you very much!
You need to login to post a reply.