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

2016/6/6

Destroying two enemies

Amelfa Amelfa

2016/6/6

#
I need help destroying two enemies in a galaga-like game i coded. In my bullet class, i can shoot and hit enemy1 and have it disappear no problem, but when my bullet hits the asteroid, i get an error saying the actor isnt in the code. I dont know how to make them both disappear with no errors. [Disallowed URL]
public class Bullet extends Actor
{
    private int speed=-5;
    /**
     * Act - do whatever the Beeper wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        setLocation(getX(),getY()+speed);
        destroyAsteroids();
        destroyEnemy1();
        //checkBoundaries();
    }    
    
    public void destroyAsteroids()
    {
        Actor asteroid=getOneIntersectingObject(Asteroid.class);
        if(asteroid !=null)
        {
            getWorld().removeObject(asteroid);
            getWorld().removeObject(this);
        }
        
    }
    
    public void destroyEnemy1()
    {
        Actor enemy1=getOneIntersectingObject(Enemy1.class);
        if(enemy1 !=null)
        {
            getWorld().removeObject(enemy1);
            getWorld().removeObject(this);
        }
        
    }
danpost danpost

2016/6/6

#
What the error is saying is that after you hit an asteroid and the bullet is removed from the world, you cannot then try to find an intersecting Enemy1 object. You cannot look for any intersecting object to an object that is not in the world (the bullet was removed). Change line 12 to this:
if (getWorld() != null) destroyEnemy1();
This will ensure that the bullet is still in the world when checking for an intersecting Enemy1 object.
You need to login to post a reply.