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

2015/2/23

Enquiry

Abanourmo Abanourmo

2015/2/23

#
This is related to a bird game. if the player (the bird) eats a food object, the game stops. I would like the game to keep running. This is what is displayed: 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.getOneObjectAtOffset(Actor.java:867) at Food.EatenbySmallBird(Food.java:44) at Food.act(Food.java:22) 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) This the code it is related to:
public void EatenbySmallBird()
       {
          Actor SmallBird = getOneObjectAtOffset(0, 0, SmallBird.class); // looks at the birds location
          if(SmallBird != null) {
            getWorld().removeObject(this); //if bird touches the food then it become null
                           
            }
       }
lordhershey lordhershey

2015/2/23

#
If EatenbySmallBird is called in the act method then when you have done the removeObject(this) the eaten object is no longer in the world, if you do anything like getX() or setLocation() after that point you will get this exception.
Super_Hippo Super_Hippo

2015/2/23

#
Show the act method of the Food class. Is the food already removed from somewhere in the act method or do you have code in the SmallBird class to eat the food? This can also cause the food to be already removed when this method is called.
danpost danpost

2015/2/23

#
Your act method is probably calling another method before it calls 'EatenbySmallBird' that can potentially remove the food from the world. If it does so, your 'EatenbySmallBird' method cannot execute the 'getOneObjectAtOffset' method because it require the actor be in a world. There are several ways to avoid the error; however, with the limited code given, the easiest of suggestions is inserting the following for the first line in the 'EatenbySmallBird' method:
if (getWorld() == null) return;
Abanourmo Abanourmo

2015/2/23

#
Thank you for your help. the code has been fixed. I over thought it. I moved the code into the bird class; instead of keeping it in the food class.
Actor birdFood;
     birdFood = getOneObjectAtOffset(0,0, Food.class);
     if(birdFood != null)
     {
         World world;
         world = getWorld();
         world.removeObject(birdFood);
        }
I put this code into the act, in my food class.
You need to login to post a reply.