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

2013/10/19

removeObject

sihaco sihaco

2013/10/19

#
Hey guys, I would like to know how to use the removeObject method. I have a shooting system. I have a class Bullet and when the bullet is shot, it has to disappear when it hits the edge of the world (atWorldEdge). However, I can't use removeObjects(), because then all bullets disappear. Only the ones that hit the edge of the world should disappear and the other should keep moving towards the edge (and eventually also disappear). This is how I use removeObjects() now:
if(atWorldEdge()){
           getWorld().removeObjects(getWorld().getObjects(Bullet.class));  
        }
I have to use removeObject, but the compiler tells me that he/she cannot find the symbol removeObject().
danpost danpost

2013/10/19

#
(1) 'removeObjects' and 'removeObject' are two different methods; one requires a list of object to remove and the other requires one Actor object to remove. (2) these method are both in the World class API and need a world object to execute them; (3) the 'this' keyword is used to reference the object that the method being executed is being run on (or for); in an Actor subclass act method it represents a specific object created from that class.
if (atWorldEdge()) {
    getWorld().removeObject(this);
This statement supplies 'this' actor object to the world so that the world can remove it when at the edge of the world.
danpost danpost

2013/10/19

#
More understandably, might be:
if (this.atWorldEdge()) {
    getWorld().removeObject(this);
}
The 'this' keyword is the default object to execute a method on (or for) if no object is explicitly given.
You need to login to post a reply.