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

2017/11/25

How to check if a defined object is still in world?

BananaJoe BananaJoe

2017/11/25

#
I need to check if a defined object still exist. But with commands like getObjects(x.class) you can only check all objects of a class. In my game I have multiple enemies and if one gets shot it is deleted. When a bullet is on the way and the enemy gets killed it throws and error. Is there a way to ask if a defined object is still in the world?
Super_Hippo Super_Hippo

2017/11/25

#
It seems like you give your bullet a target and it should follow that target until it hits it. You can use
1
2
3
4
if (target.getWorld() != null)
{
    //...
}
to make sure the object is still in the world. ('target' should be the object which is the target)
BananaJoe BananaJoe

2017/11/25

#
It throwes the same error as before (java.lang.IllegalStateException: Actor not in world. An attempt was made to use the actor's location while it is not in the world. Either it has not yet been inserted, or it has been removed.) by "target.getWorld() != null" when the target gets deleted before the bullet reaches it. Here`s the code btw.:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Bullets extends Actor
{
    Bloons target;
    public Bullets(Bloons bloon)
    {
        target = bloon;
    }
     
    public void aim()
    {
        if(target.getWorld() != null)
        {
            turnTowards(target.getX(), target.getY());
            move(5);
        }
        else
        {
            getWorld().removeObject(this);
        }
    }   
}
Super_Hippo Super_Hippo

2017/11/25

#
From where do you call the 'aim' method?
BananaJoe BananaJoe

2017/11/25

#
From a subclass called CannonBullet, here`s the sript:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class CannonBullet extends Bullets
{
     public CannonBullet(Bloons bloon)
    {
        super(bloon);
    }
     
    public void act()
    {
        aim();
        if(getX() < target.getX() + 5 && getX() > target.getX() - 5 && getY() < target.getY() + 5 && getY() > target.getY() - 5 && target.getWorld() != null)
        {
            getWorld().removeObject(target);
            getWorld().removeObject(this);
        }
    }
}
Super_Hippo Super_Hippo

2017/11/25

#
So that's the problem. In line 11 you are trying to get the target's location without checking if it is in the world. You either have to check it again there or move lines 11-15 into the aim method.
BananaJoe BananaJoe

2017/11/25

#
Oh, thank you for your help, in both cases. :)
You need to login to post a reply.