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

2017/3/14

An actor checking whether another actor exists

timothytitus timothytitus

2017/3/14

#
I have a dragon class that shoots fireball class. Fireball constantly gets information from the dragon. Therefore, i need the fireball to check whether the dragon still exists in the world so the code won't crash. Is there a way for the fireball to check whether the dragon exists.
danpost danpost

2017/3/14

#
What code are you using to access the dragon object while it exists?
timothytitus timothytitus

2017/3/14

#
    public void movement()
    {
        if (( gotDirection == false) && (getWorld() != null))
        {
            direction = getWorld().getObjects(Dragon.class).get(0).direction();
            gotDirection = true;
    }    
            move(direction * 5);
}  
This is from my fireball class which takes the direction of the Dragon class to determine its whether it moves left or right. My game crashes sometimes when the dragon is destroyed while the fireball is up. I don't know why because this code shouldn't run anymore when gotDirection = true java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 is my error
Super_Hippo Super_Hippo

2017/3/14

#
Try this:
//Dragon creates fireball
Fireball f = new Fireball();
getWorld().addObject(f, getX(), getY());
f.setDirection(direction);
//in Fireball
private int direction;

//in act:
move(direction*5);

//method to set the direction when creating
public void setDirection(int d)
{
    direction = d;
}
timothytitus timothytitus

2017/3/15

#
Okay thanks I'll try
You need to login to post a reply.