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

2012/3/7

Health

Dom Dom

2012/3/7

#
I want my actor to lose health every time he touches an enemy, gets burnt, touches spikes, or falls down a hole. And I would like my actor to gain health if it eats something. How do I go about coding something like this? After I have done that I would like to link this to danposts healthbar that he posted at http://www.greenfoot.org/scenarios/4114 How do I do this?
Duta Duta

2012/3/7

#
If you look in danpost's Bar.class, you'll see that there are the methods: - public void add(int amount) - public void subtract(int amount) You call these methods to add or subtract health. There are other ways to do this but here's one way: (1) Go to your world class. Add the following:
public class YourWorldName extends World
{
    public Bar hpBar;

    public YourWorldName()
    {
        super(worldWidth, worldHeight, 1);
        //Replace the parameters with what you want.
        hpBar = new Bar("Player:", "HP", startingHealth, maximumHealth));
        addObject(hpBar, xPosition, yPosition);
        
        //The rest of your constructor
    }
    
    //The rest of the class
}
(2) In the actor you are damaging/healing, do the following:
public YourActor extends Actor
{
	Class[] damagingClasses = {
		Enemy.class,
		Fire.class,
		Spike.class
	};
	
	public void act()
	{
		checkForDamage();
		checkForHealing();
		
		//The rest of your act() method
	}

	private void checkForDamage()
	{
		int damageAmount = 40; //Change this to whatever
		for(Class clss : damagingClasses)
			if(isTouching(clss))
				((YourWorldName)getWorld()).hpBar.subtract(damageAmount);
	}
	
	private void checkForHealing()
	{
		//I've left this method not done
		//so you can try to do it - I find
		//the best way to learn is through
		//attempting it yourself.
	}

	private boolean isTouching(Class clss)
	{
		return getOneIntersectingObject(clss) != null;
	}
}
PLEASE BEAR IN MIND: This may not work (I haven't tried it myself, and don't even know if you can have a Class array. This also has the same damage for each of the damaging things. It may also be syntactically incorrect as I typed it straight into the reply box without testing it in Greenfoot. I've also not done the "falling down a hole" as I noticed that had been done here. I assumed fire, spikes and enemy's to have seperate classes of those names (see damagingClasses)
You need to login to post a reply.