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

2015/7/11

Error: actor not in the world

happy123 happy123

2015/7/11

#
How do you fix this error?? this is my code
import greenfoot.*;

/**
 * Write a description of class Rocket here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Rocket extends Actor
{
    /**
     * Act - do whatever the Rocket wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        
        if (Greenfoot. isKeyDown ("space"))
        {
            fire();
        }   
        
        if (Greenfoot. isKeyDown ("W"))
        {
            move(3);
        }
        
        if (Greenfoot. isKeyDown ("S"))
        {
            move(-3);
        }
        
        if (Greenfoot. isKeyDown ("A"))
        {
            turn(-5);
        }
        
        if (Greenfoot. isKeyDown ("D"))
        {
            turn(5);
        }
        touch();
        touching();
    }
    
    public void fire()
    {
        if (getWorld(). getObjects(Bullet.class).isEmpty())
        {
            Bullet bala = new Bullet();
            getWorld().addObject (bala, getX(), getY());
            bala.setRotation(getRotation());
            bala.move(50);
             
        }
    }
    
    public void touch()
    {
       if ( isTouching(Bullet2.class) )
       { 
           getWorld().removeObject(this);
           Greenfoot.stop();
           return;
       }
       
    }
           
    public void touching()
    {
        if ( isTouching(Bomb.class) )
        { 
           getWorld().removeObject(this);
           Greenfoot.stop();
           return;
        }
    }
}
danpost danpost

2015/7/11

#
Both methods, 'touch' and 'touching' could possibly remove the actor from the world. If the first one called from the act method does remove it, you must not allow the second one to be called. You can either check if the actor is still in the world before calling the second one; or you can have the first one called return a boolean value indicating whether it was removed or not; or, you could combine the methods into a single method since the internal codes of both 'if' blocks are identical.
You need to login to post a reply.