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

2014/10/30

Disappearing at both edges of the world?

DiplomatikCow DiplomatikCow

2014/10/30

#
I have ghosts that spawn from the left side of the world and move right, and vice versa. However, when I go to remove them when they reach their opposite end, I can only remove from one end.
  setLocation(getX()+speed, getY());
        if(getX()>=getWorld().getWidth()-1)
        {
            getWorld().removeObject(this);
        } 
        if(getX()>=getWorld().getWidth()+1)
        {
            getWorld().removeObject(this);
        } 
When I have it like this, a error pops up, saying
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:681) at greenfoot.Actor.getX(Actor.java:157) at Ghost.act(Ghost.java:17) at greenfoot.core.Simulation.actActor(Simulation.java:583) at greenfoot.core.Simulation.runOneLoop(Simulation.java:541) at greenfoot.core.Simulation.runContent(Simulation.java:215) at greenfoot.core.Simulation.run(Simulation.java:205)
How do I fix this so I can have both types of moving ghosts get removed?
danpost danpost

2014/10/30

#
First, I do not think you will remove any at 'getWorld().getWidth()+1'. If that is to remove the ones that go from right to left, that value would be literally a world away from what you want to use. You have two different conditions that you want to use that each would remove a ghost from the world. You can combine the conditions into one 'if' clause and avoid throwing the IllegalStateException by using a conditional operator (see this page of the java tutorials).
Alwin_Gerrits Alwin_Gerrits

2014/10/31

#
Why not make your ghosts spawn at setLocation(1, randomY) and setLocation(getWorld().getWidth()-1, randomY)? Then all you have to do is make the next statement:
if(isAtEdge()) 
{getWorld().removeObject(this);}
That way you ghost spawn at 1 pixel from each edge and if they come in contact with any side of the screen they disappear. If you don't want them to disappear when hitting the top and bottom you make if(isAtEdge()) into:
if(isAtEdge() && getY()<getWorld().getHeight() && getY()>0)
DiplomatikCow DiplomatikCow

2014/10/31

#
Thank you, I got it figured out.
You need to login to post a reply.