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

2015/6/15

Wall crash

17jrousso 17jrousso

2015/6/15

#
    public void atEdge()
    {
        if(getX()<=1)
        {
            getWorld().removeObject(this);
        }
    }
It gives me this error java.lang.IllegalStateException: Actor not in world. An attempt was made to use the actor's location while it is not in the world. Either it has not yet been inserted, or it has been removed. at greenfoot.Actor.failIfNotInWorld(Actor.java:663) at greenfoot.Actor.getX(Actor.java:157) at WallRect.act(WallRect.java:17) at greenfoot.core.Simulation.actActor(Simulation.java:568) at greenfoot.core.Simulation.runOneLoop(Simulation.java:526) at greenfoot.core.Simulation.runContent(Simulation.java:215) at greenfoot.core.Simulation.run(Simulation.java:205) The line 17 it is talking about is to is
setLocation(getX()-speed, getY());
The problem is that one wall is deleted at the edge of the world, then the program crashes and gives error above. I would like both walls to be deleted at the same time (The walls reach the edge of the world at the same time).
danpost danpost

2015/6/15

#
If both walls are placed into the world at the same x-coordinate location within the same code fragment, then they will both reach the left edge of the world at the same time and they can each remove themselves at that time:
public void act()
{
    setLocation(getX()-speed, getY());
    if (getX() <= 0) getWorld().removeObject(this);
}
The act method will run for both walls each act cycle and both will be removed on the same cycle. The error was mainly due to the order of execution of the two lines. You were checking for edge and potentially removing the actor before having the actor move. If removed, you cannot get its location because it no longer has one. By moving the actor first, there is no issue in this regard.
You need to login to post a reply.