When my enemy has been hit by a bullet 5 times, I want it to be removed from the world. However, when my enemy is removed I receive the error saying that it cannot remove something that is not there. I am aware that this means that the remove object is being called even after the enemy has died, but I can't work out how to stop this.
The following is the code for my enemy and then the bullet:
public class EnemyNormal extends Actor
{
private int health = 100;
/**
* Act - do whatever the EnemyNormal wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void setHealth (int points)
{
health += points;
}
public int getHealth()
{
return health;
if (health <= 0)
{
getWorld().removeObject(this);
}
}
public void act()
{
move(4);
if (Greenfoot.getRandomNumber(100) < 10)
{
turn(Greenfoot.getRandomNumber(90) - 45);
}
if (getX() <= 100 || getX() >= getWorld().getWidth() - 100)
{
turn(180);
}
if (getY() <= 100 || getY() >= getWorld().getWidth() - 100)
{
turn(180);
}
}
}{
/**
* Act - do whatever the Bullet wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void hitEnemy()
{
EnemyNormal enemynormal = (EnemyNormal) getOneObjectAtOffset(0, 0, EnemyNormal.class);
if(enemynormal != null)
{
enemynormal.setHealth(-20);
getWorld().removeObject(this);
}
}
public void act()
{
move(10);
hitEnemy();
}
}
