hola
public void recoverHealth() {
++life;
}
final Actor heart = getOneIntersectingObject(Heart.class);
if (heart != null) {
getWorld().removeObject(heart);
healthBar.recoverHealth();
}final HealthBar healthBar = getWorld().getObjects(HealthBar.class).get(0);
import greenfoot.*;
public class Player extends Actor
{
private final int maxHealth = 3600; // adjust as needed
private Bar bar;
private int health;
protected void addedToWorld(World world)
{
if (bar == null) bar = new Bar();
world.addObject(bar, 100, 30); // or 'addObject(bar, getX(), getY()-50);' if bar is to stay with player on screen
}
public void act()
{
if (/** any condition the causes health to change */)
{
// any non-bar actions here (like removing an object)
bar.add(-10); // adjust value as needed; a negative value decreases health
}
// repeat for each condition that changes health
// at end of act
if (health == 0) getWorld().removeObject(this);
}
/** Bar class */
protected class Bar extends Actor
{
public Bar()
{
add(maxHealth); // start bar with full health
}
protected void add(change)
{
// adjust health
health += change;
if (health < 0) health = 0;
if (heatlh > maxHealth) health = maxHealth;
// determine bar width (percentage of health)
int pct = health*100/maxHealth;
// create and set new image for bar
GreenfootImage image = new GreenfootImage(104, 24);
image.drawRect(0, 0, 103, 23);
image.drawRect(1, 1, 101, 21);
/**
* Could replace the last 2 lines with the following
*
* image.fill();
* image.setColor(Color.WHITE);
* image.fillRect(2, 2, 102, 22);
*/
if (pct != 0)
{
GreenfootImage indicator = new GreenfootImage(pct, 20);
indicator.setColor(Color.GREEN);
indicator.fill();
image.drawImage(indicator(2, 2);
}
setImage(image);
}
}
}private void catch_gas()
{
if (isTouching(Gas.class))
{
removeTouching(Gas.class);
Greenfoot.playSound("gas.wav");
bar.add(10); // adjust change (value) as needed
}
}