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

2017/5/25

Bullet removal error

Kevroa Kevroa

2017/5/25

#
Hi, I'm having a bit fo trouble with my code and I don't understand why it doesn't work. I just need help getting it to work to continue with my game. Basically I have an enemy that creates this Bullet object and once the bullet hits a wall, player, or edge of the world, it gets destroyed. My problem is that once it gets destroyed, the code still tries to run and an error pops up saying "Actor not in world." Heres my code:
public class Bullet extends Actor
{
    /**
     * Act - do whatever the Bullet wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        if (Bullet.class != null)
        {
            move(-3);
            BulletCollision();
        }
    }   
    public Bullet()
    {
        GreenfootImage image = getImage();
        image.scale(20,20);
        setImage(image);
    }
    public void BulletCollision()
    {
        if (Bullet.class != null)
        {
            Actor Wall = getOneIntersectingObject(Wall.class);
            if (Wall != null)
            {
                getWorld().removeObject(this);
            }
            if (getX() == 0 || getX() == 399)
            {
                getWorld().removeObject(this);
            }
            Actor Player = getOneIntersectingObject(Player.class);
            if (Player != null)
            {
                getWorld().removeObject(this);
            }
        }
    } 
}
I tried to get the code to work through the use of the if statements that ask if the bullet in the world or not... but it didnt work.
danpost danpost

2017/5/25

#
Insert the following after each of lines 28, 32 and 37:
return;
Yehuda Yehuda

2017/5/25

#
Doing the 'if' statements that you did doesn't check if the actor is in the world, so they should be removed. The problem is that you remove the bullet on line 28 but then try to getX() right after that, or you remove the bullet on line 32 then try to call the getOneIntersectingObject method which throws an exception if the actor is not in the world. Try adding in 'return;' after lines 28 and 32. Beaten to it.
Kevroa Kevroa

2017/5/25

#
Ah, Thanks! Makes sense... don't know why I didn't think of that. Will try in a few minutes...
You need to login to post a reply.