What I want with this method is that when I eat gas, my life recovers little by little
public class Gasolina extends Actor
{
private final Health health = new Health();
@Override
protected void addedToWorld(final World world)
{
world.addObject(health, 100, 30); // or 'addObject(bar, getX(), getY()-50);' if bar is to stay with player on screen
}
@Override
public void act()
{
catch_gas();
}
private void catch_gas()
{
final Actor gas = getOneIntersectingObject(Gas.class);
if (gas != null)
{
getWorld().removeObject(gas);
Greenfoot.playSound("gas.wav");
health.recover();
}
}
protected class Health extends Actor {
private static final int MAX_HEALTH = 10;
private static final int LOSE_HEALTH_PERIOD = 120;
private final int healthBarWidth = 40;
private final int healthBarHeigth = 10;
private final int pixelsPerHealthPoint = healthBarWidth / MAX_HEALTH;
private int currentFrame = 0;
private int health = MAX_HEALTH;
@Override
public void act()
{
checkForHealthLoss();
update();
}
public void update()
{
setImage(new GreenfootImage(healthBarWidth + 2, healthBarHeigth + 2));
GreenfootImage myImage = getImage();
myImage.setColor(Color.WHITE);
myImage.drawRect(0,0, healthBarWidth + 1, healthBarHeigth + 1);
myImage.setColor(Color.GREEN);
myImage.fillRect(1, 1, health*pixelsPerHealthPoint, healthBarHeigth);
}
private void checkForHealthLoss()
{
++currentFrame;
if (currentFrame == LOSE_HEALTH_PERIOD)
{
lose();
currentFrame = 0;
}
}
public void lose()
{
health--;
if (health == 0)
{
endGame();
}
}
public void recover()
{
health++;
}
private void endGame()
{
getWorld().addObject(new GameOver(), getWorld().getWidth()/2, getWorld().getHeight()/2);
Greenfoot.stop();
}
}
}