I´m building my own Space Invaders in Java with Greenfoot and I have a Spaceship which shoots the Aliens, but the Bullets stop at the top of the map and stay there so I wrote this method which should remove a bullet if it hits the top of the but it doesn't work. What´s the problem?
public void disappearIfOnTop() {
Actor Bullet = getOneIntersectingObject(Actor.class);
getY();
if(getY() == 0) {
World world;
world = getWorld();
world.removeObject(Bullet);
}
}
Edit: they are getting removed if they hit another bullet which is stuck on the top.
The method getOneIntersectingObject()
returns a null
if there is no other actor.
You might want to check this to be sure:
public void disappearIfOnTop() {
if (getY() == 0) {
Actor bullet = getOneIntersectingObject(Actor.class);
if (bullet == null) {
setLocation(getX(), 50); // move down if no other is around
} else {
setLocation(getX(), 100); // move further down if another is around
}
}
}
If the method getOneIntersectingObject()
returns a reference to an actor, your current method is removing that one, not the one who is at Y=0. (BTW, don't use variable names starting with uppercase letters. By convention, this is reserved for classes.)
You can simplify your method to:
public void disappearIfOnTop() {
if (getY() == 0) {
getWorld().removeObject(this);
}
}