I've created a Healthbar, but it only works when my objects hits another.
So while my actor is unprotected, he has only one life. But as soon as he hits the other object, he has two lifes.
So he hits the joker which gives him an extra life. Well, it doesn't work so far.
Here's my code so far:
The class of my main character:
The class of my Healthbar:
if (isTouching(Stein.class))
{
removeTouching(Stein.class);
Actor dementor = getOneIntersectingObject(Dementor.class);
if(dementor!=null)
{
World myWorld = getWorld();
Hogwarts hogwarts = (Hogwarts)myWorld;
HealthBar2 healthbar2 = hogwarts.getHealthBar2();
if(touchingDementor == false)
{
healthbar2.loseHealth();
touchingDementor = true;
if(healthbar2.health <= 0)
{
myWorld.removeObject(this);
}
}
}
else
{
touchingDementor = false;
}
}public class HealthBar2 extends Actor
{
int health = 2;
int healthBarWidth = 80;
int healthBarHeight = 15;
int pixelsPerHealthPoint = (int)healthBarWidth/health;
public HealthBar2()
{
update();
}
public void act()
{
update();
}
public void update()
{
setImage(new GreenfootImage(healthBarWidth + 2, healthBarHeight + 2));
GreenfootImage myImage = getImage();
myImage.setColor(Color.WHITE);
myImage.drawRect(0, 0, healthBarWidth + 1, healthBarHeight + 1);
myImage.setColor(Color.RED);
myImage.fillRect(1, 1, health*pixelsPerHealthPoint, healthBarHeight);
}
public void loseHealth()
{
health--;
}
