Hey, I have a code, where when Bullet object touches Enemy object, it lowers it´s health, the health bar is constucted in EnemyHealthBar class.
Enemy code:
Bullet code:
EnemyHealthBar code:
The problem is that it lowers health of all Enemy objects, not just one.
public class Enemy extends Actor { static int health = 300; protected void addedToWorld(World world) { getWorld().addObject(new EnemyHealthBar(), getX(), getY()); } public void hit() { health -= 10; }
import java.util.List; public class Bullet extends Actor { int chance; int mouseDirection; public Bullet(){ setRotation(Player.mouseDirection); } public void act() { move(10); if (isTouching(Enemy.class)){ chance = Greenfoot.getRandomNumber(10); if (chance == 5) getWorld().addObject(new Medkit(), getX(), getY()); List<Enemy> enemys = getIntersectingObjects(Enemy.class); if (enemys != null && !enemys.isEmpty()) { for (Enemy enemy : enemys) { enemy.hit(); } } getWorld().removeObject(this); } else { if (isAtEdge()) getWorld().removeObject(this); } } }
public class EnemyHealthBar extends Actor { int healthBarWidth = 300; int healthBarHeight = 3; int pixelsPerHealthPoint = healthBarWidth/Enemy.health; public void act() { update(); setLocation(Enemy.enemyX, Enemy.enemyY); } public void update() { setLocation(Enemy.enemyX, Enemy.enemyY - 25); setImage(new GreenfootImage(healthBarWidth + 2, healthBarHeight + 2)); getImage().setColor(Color.BLACK); getImage().drawRect( 0, 0,healthBarWidth + 1,healthBarHeight + 1); getImage().setColor(Color.YELLOW); getImage().fillRect( 1, 1, Enemy.health*pixelsPerHealthPoint, healthBarHeight); setLocation(Enemy.enemyX, Enemy.enemyY - 25); } }