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

2014/6/12

Program crashes when I try removing an actor.

semigu semigu

2014/6/12

#
Whenever I try to run my game, the game crashes when I remove both the bomb, and the cannonball. If I take the out get.World.removeObject(this); the game works fine, however the projectile cannonball is still present and keeps on going. I only want to get rid of the bomb and the cannonball together.
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class CannonBall here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class CannonBall extends Mover
{

    /**
     * Act - do whatever the CannonBall wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {

        move (20);
        checkBomb();

        if (this.atWorldEdge()==true)
        {World world;
            world = getWorld();
            world.removeObject(this);
            return;
        }

    }

    public void checkBomb()
    {
        if (getWorld() != null) {

            Actor Bomb = getOneIntersectingObject(Bomb.class);
            if (Bomb != null)
            {
                getWorld().removeObject(Bomb);
                getWorld().removeObject(this);
                return;
            }
        }
    }
}
danpost danpost

2014/6/12

#
Here are three different ways you can conquer this:

First way

Insert the following line at line 21:
if (getWorld() == null) return;

Second way

change line 22 to this:
if (getWorld() != null && atWorldEdge())

Third way

Change the class to this:
import greenfoot.*;

public class CannonBall extends Mover
{
    public void act() 
    {
        move (20);
        if (foundBomb() || atWorldEdge()) getWorld().removeObject(this);
    }

    private boolean foundBomb()
    {
        Actor bomb = getOneIntersectingObject(Bomb.class);
        if (bomb != null)  getWorld().removeObject(bomb);
        return bomb != null;
    }
}
semigu semigu

2014/6/12

#
Thanks danpost! I'll try this asap, and i'll let you know if it works!
semigu semigu

2014/6/13

#
THANK YOU SO MUCH DANPOST! The first one worked fine!!
You need to login to post a reply.