This site requires JavaScript, please enable it in your browser!
Greenfoot back
tallyaka
tallyaka wrote ...

2012/3/18

Health Hearts

tallyaka tallyaka

2012/3/18

#
Ok, I've got 4 images of hearts. One with 3 one with 2, 1, 0. I want to make it so that when the variable "health" is at 1 it shows 1 heart, when at 2 it shows 2 hearts,etc. How would I do this?
danpost danpost

2012/3/18

#
The easiest way is to set up an array of images, like so:
GreenfootImage[] hearts = { new GreenfootImage("no_hearts.jpg"),
                            new GreenfootImage("one_heart.jpg"),
                            new GreenfootImage("two_hearts.jpg"),
                            new GreenfootImage("three_hearts.jpg") }
int health = 3;

private void updateImage()
{
    setImage(hearts[health]);
}
Just change the filenames appropriately, and when the health value changes, call the updateImage method.
tallyaka tallyaka

2012/3/18

#
Ok, I did this but how do I add the hearts into the scenario. Just using getWorld().addObject(hearts, int, int); doesn't seem to work.
danpost danpost

2012/3/18

#
The code I provided should be in an Actor sub-class, best called 'Hearts'. The constructor for the Hearts class would simply be
public Hearts()
{
    updateImage();
}
and you could add this method
public void adjustHearts(int adjustmentValue)
{
    health += adjustmentValue;
    if (health > 3) health = 3;
    if (health == 0) Greenfoot.stop();
    else updateImage();
}
Then, in the world class constructor, add the Heart object as follows:
addObject(hearts, x, y);
with the world class variable hearts defined as
public Hearts hearts = new Hearts();
In your player actor class, when loses health, get a reference to your world sub-class (WorldSubClass) to access the Hearts object with
WorldSubClass worldsubclass = (WorldSubClass) getWorld();
worldsubclass.hearts.adjustHearts(-1);
tallyaka tallyaka

2012/3/18

#
I'm obviously getting better at this because I actually understood what that was doing just by looking at it :) This worked perfectly! Thanks!!!
You need to login to post a reply.