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

2013/3/26

Need help removing actor when touched by another

AA123 AA123

2013/3/26

#
I am trying to make an actor remove itself when touched by another actor but get the java.lang.IllegalStateException: Actor not in world. error. This is the code for getting the actor to remove itself: public void getEatenbyFly(){ Actor burger; burger = getOneObjectAtOffset(0,0, Fly.class); if (burger != null){ getWorld().removeObject(this); return;} } public void getEatenbyAnt(){ Actor burger; burger = getOneObjectAtOffset(0,0, Ant.class); if (burger != null){ getWorld().removeObject(this); return;} } Thanks in advance!
AA123 AA123

2013/3/26

#
I mean, thanks in advance if anyone could help!
danpost danpost

2013/3/26

#
The problem is not in either of these methods. The problem is in the combination of these methods. I believe you are calling both these methods from your 'act' method. If your burger is removed by the first called method then an error will ensue from the second when 'getOneObjectAtOffset' is called (cannot get an offset to something that has been removed from the world). To fix this adjust the calls in your 'act' method to something like the following:
getEatenbyFly();
if (getWorld() == null) return; // insert this line
getEatenbyAnt();
if (getWorld() == null) return; // may need to do it again
Your methods are not really clear as to what they are doing. In both those given above you are naming the object that 'eats' the burger a 'burger'. Better would be this:
public void getEatenbyFly()
{
    Actor fly = getOneObjectAtOffset(0, 0, Fly.class);
    if (fly != null) getWorld().removeObject(this);
}

public void getEatenbyAnt()
{
    Actor ant = getOneObjectAtOffset(0, 0, Ant.class);
    if(ant != null) getWorld().removeObject(this);
}
In other words, when referencing a fly, call it a fly (not a burger). And the same with an ant.
AA123 AA123

2013/3/26

#
Thank you so much Danpost! It worked!
danpost danpost

2013/3/26

#
Another way to handle this is to combine the two methods into one, supplying the class to check for in a parameter field. Have the method return a boolean indicating whether an object was found or not. This is how it would be done:
// the method would be
public boolean gotEatenBy(Class clss)
{
    Actor actor = getOneObjectAtOffset(0, 0, clss);
    if (actor == null) return false;
    // 'else' is understood here (either the method is exited or it is not)
    getWorld().removeObject(this);
    return true;
}
// then you would have this in your 'act' method
if (gotEatenBy(Fly.class) || gotEatenBy(Ant.class)) return;
You need to login to post a reply.