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

2012/1/21

How do you check if an object is currently added to the world?

Duta Duta

2012/1/21

#
I'm scanning the API's but not coming across any nice booleans :/
Duta Duta

2012/1/21

#
Just thought of a method for checking, will post again if it doesn't work..
Duta Duta

2012/1/21

#
It worked - here's the code if anyone's interested: (anActor is the actor you're checking)
public boolean isInWorld(Actor anActor)
{
    for(int i = 0; i < getWorld().getObjects(null).size(); i++)
    {
        if(anActor.equals(getWorld().getObjects(null).get(0))) return true;
    }
    return false;
}
davmac davmac

2012/1/22

#
Err, that doesn't work. :) Maybe this would work:
public boolean isInWorld(Actor anActor)
{
    for(int i = 0; i < getWorld().getObjects(null).size(); i++)
    {
        if(anActor == getWorld().getObjects(null).get(i)) return true;
    }
    return false;
}
(Notice I get(i) rather than get(0), and use '==' to compare which is ok - and faster - in this case, although .equals() also works). However if that works it's really only by chance - there's no guarantee that getObjects(...) returns a list in the same order each time you call it. So, even better would be:
public boolean isInWorld(Actor anActor)
{
    List l = getWorld().getObjects(null);
    for(int i = 0; i < l.size(); i++)
    {
        if(anActor == l.get(i)) return true;
    }
    return false;
}
But, there's a much simpler and faster way, which is:
public boolean isInWorld(Actor anActor)
{
    return anActor.getWorld() != null;
}
Or, if you're worried about the possibility that the actor may be in a different world, you can use:
public boolean isInWorld(Actor anActor)
{
    return anActor.getWorld() == getWorld();
}
Duta Duta

2012/1/22

#
I meant get(i) >.< and I generally do save it to a list, was just in a hurry though, and didn't realise that it changes the order. Thanks :)
davmac davmac

2012/1/22

#
No problem. By the way you can also do:
public boolean isInWorld(Actor anActor)
{
    return getWorld().getObjects(null).contains(anActor);
}
... however the way I showed you before is the best way. There are lots of ways to accomplish the same thing :)
Duta Duta

2012/1/22

#
davmac wrote...
No problem. By the way you can also do:
public boolean isInWorld(Actor anActor)
{
    return getWorld().getObjects(null).contains(anActor);
}
... however the way I showed you before is the best way. There are lots of ways to accomplish the same thing :)
Oh, that's a good idea - having not done a whole lot with Lists I'd forgotten all about contains() - I prefer working with arrays myself, even if they are "worse" generally
You need to login to post a reply.