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

2016/5/6

Need help with terminal error. Actor not in world

jmsmall jmsmall

2016/5/6

#
So I have an actor that I want to constantly moving to where my main character is moving. So I have two integers that find the X and Y of the "Hero". Then it sets the location of the actor to the Hero. Problem is, when run it, I get an error saying, "Actor not in world. An attempt was made to use the actor's location while it is not in the world." Even though my actor is saved into the world and is visible. Here is the code for the actor that I want to set the location of.
import greenfoot.*;

/**
 * Write a description of class Invisibru here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Invisibru extends Actor
{
    Hero hero = new Hero();
    
    /**
     * Act - do whatever the Invisibru wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        move();
    } 

    public void move()
    {
        int X = hero.getX();
        int Y = hero.getY();
        setLocation(X, Y);
    }
}
Any idea why it's not working?
valdes valdes

2016/5/6

#
The problem is that hero is not in the world, because hero does not reference to your main character. You need to link the hero variable to the Hero object in your world. Here is a suggestion:
public class Invisibru extends Actor
{
    private Hero hero; // no new, you dont need a new hero
     
    public Invisibru(Hero hero) {
        this.hero = hero;
    }
    /**
     * Act - do whatever the Invisibru wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        move();
    } 
 
    public void move()
    {
        int X = hero.getX();
        int Y = hero.getY();
        setLocation(X, Y);
    }
}
In your world class, or wherever you create the Hero and Invisibru objects
Hero hero = new Hero();
addObject(hero, x, y);

//after the creation of hero and placement of hero in the world
Invisibru invisibru = new Invisibru(hero);
addObject(invisibru, x, y);
danpost danpost

2016/5/6

#
With the code suggested by valdes, your hero must remain in the world. If at some later time (or even now), you decide that the hero should be removed from the world for some reason, the code here will fail. A simple adjustment will assure that no changes elsewhere in your code will cause any problems. Change the act method given to:
public void act()
{
    if (hero.getWorld() != null) move();
}
The 'move' method should probably be made a 'private' method so that it cannot be called from outside the class.
You need to login to post a reply.