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

2014/3/25

Help!

rhyleymaster rhyleymaster

2014/3/25

#
Hi! I am currently trying to make a mouse-style shooting game, however I have run into an issue. Every time a bullet hits a wall or enemy, the game pauses, and the error terminal pops up. The error i get is in the bullet code, at line 13. Here is the bullet code:
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

public class Bullet extends Actor
{
   public void act()  
   {  
       move(6);
       checkBoundaries();
       kill();
   }
   
   public void kill() {
       Actor enemy = getOneIntersectingObject(Enemy.class);      
       if(enemy != null) {  
            getWorld().removeObject(enemy);
            getWorld().removeObject(this);
       }  
    }
    
   public void checkBoundaries() {
       if(getX() > getWorld().getWidth() - 3)
            getWorld().removeObject(this);
            else if(getX() < 3)
            getWorld().removeObject(this);
            else if(getY() > getWorld().getHeight() - 3)
            getWorld().removeObject(this);
            else if(getY() < 3)
            getWorld().removeObject(this);     
   }
}
Thanks!
danpost danpost

2014/3/25

#
The problem is that both 'checkBoundaries' and 'kill' could remove the actor from the world. No matter what order you have those calls in (in the act method), if the first one removes the actor, the second one will throw an 'IllegalStateException'. This is because the field 'getWorld' returns is set to 'null' the instant you 'removeObject' the actor from the world. You cannot perform any actions (collision checking, getting world coordinates, etc.) that require the actor be in the world after 'removeObject' is executed. This all being said, a simple fix would be (from your code above), to change line 9 to
if (getWorld() != null) kill();
putting the condition on calling 'kill' that the actor be in a world.
rhyleymaster rhyleymaster

2014/3/25

#
Thanks Danpost! That fiixed it.
You need to login to post a reply.