Build a 2D Top Down Game – Zero to Published – Part 7

Welcome to Part 7! In part 7 I will discuss adding health bars to spiders and providing a way for spiders to deal damage to the skeleton!  When the skeleton runs out of health, he will restart the level.

Part 1:  Getting Started

Part 2: Animations

Part 3: Prefabs

Part 4: Enemies

Part 5: Modular Scripting

Part 6: Timed Prefab Instantiation

Part 7: Health Bars

Part 8: Finishing Touches

Part 9: Publishing

Create the Health Bar

Make sure the Health BG and Health Bar Image files are in the sprites folder.  If not please grab them from the link in Article 1 and import them as sprites in the sprites folder. Add Health and HealthBG to the scene. Create a new game object, name it healthBar and put these two under it. Then put the HealthBar as a child under the skeleton. healthbarOBJ Change the Health material color to Green. healthGreen Open the Character Script and add 5 properties and 3 functions.

 

//this will need to be set to the  
//health bar renderer you wish to use. 
public SpriteRenderer healthBar; 
public int maxHealth = 100;

private int health = 100;
private Vector2 healthScale;
private Action deathFunction = () => {};

public void AdjustHealth(int amount) 
{
	//adjust current health by amount.
	this.health+=amount;

	//make sure character can't surpass max health
	if(this.health > this.maxHealth)
	{
		this.health = maxHealth;
	}
	else if(this.health < 0)
	{
		//execute the death function 
		this.deathFunction();
	}

	//update the health bar with new amount
	this.UpdateHealthBar();
}

/// <summary> 
/// returns the current health.
/// </summary> 
/// <returns>current health amount.</returns>
public int GetHealth()
{
	return this.health;
}

/// <summary> 
/// Updates the health bar length and color based on current health.
/// </summary>
private void UpdateHealthBar()
{
	// Set the health bar color between Red and Green based on current health.
	healthBar.material.color = Color.Lerp(Color.green, Color.red, 1 - this.GetHealth() * 0.01f);

	// Set the scale of the health bar to be proportional to the player's health.
	healthBar.transform.localScale = new Vector3(healthScale.x * this.GetHealth() * 0.01f, 1, 1);
}

For now, don’t worry about the DeathFunction.  The syntax might look a little funny to you, but we will be resetting it in a later part when we talk about delayed execution and dynamic code.  For now DeathFunction does nothing. Also within the start function, Initialize the HealthScale. healthScale=healthBar.transform.localScale;

Give enemies a way to damage the player.

Make sure the skeleton is tagged as the player Give the EnemyAI some new variables we will need.

 

//amount of damage to do to the player
public int damage = 5;

//how fast this can deal damage
public float damageFrequency = 1.0f;

//internal timer to track last time dealt damage.
private float damageTimer;

 

Add the following line inside the Awake() function.

 

//set internal timer for damagefrequency
this.damageTimer = this.damageFrequency;

 

Add the following lines of code inside the EnemyAI’s OnCollide function.

//make sure we don't do too much damage to the player
if (other.gameObject.tag == "Player" && this.damageTimer > this.damageFrequency)
{
//deal some damage!
other.gameObject.GetComponent<CharacterScript>().AdjustHealth(-1 * this.damage);

//reset the timer so we don't damage too much again.
this.damageTimer = 0.0f;
}

Make sure you set the Sprite Renderer of the HealthBar in the public properties of the script now.  This can be a bit challenging to find the correct health renderer.  It might help to rename it to “SkeletonHealthBar”, then use the little circle next to the property to find it and then rename it back.  Make sure you create the same object hierarchy for the spiders just like you did for the skeleton and find the same healthbar renderer for it as well.

characterScriptWithRenderer

Restarting the Level.

If you have not already done so, create a new script called “HeroScript” and drop it onto the skeleton.  Ensure you also drop the skeleton prefab back onto the skeleton.  From within this script we will do two things.

  1. Add a variable:
    //reference to the character script
    private CharacterScript character;

    ;

  2. Modify the start script to have the below code.
  3. /// <summary>
    /// Used for initialization, called after awakes are called.
    /// </summary>
    void Awake() 
    {
    	this.character = this.GetComponent<CharacterScript>();
    	character.SetDeathFunction( () =>
    		{
    			Application.LoadLevel(Application.loadedLevelName); 
    		});
    }
    
    

What we are doing is calling into the character’s death script which is executed when the character runs out of health and for the hero, ensuring that the code executed at that time is loading the currently loaded level.

Challenge: See if you can have the player do damage to the spiders in the same way.

3 thoughts on “Build a 2D Top Down Game – Zero to Published – Part 7

  1. Pingback: floyd

  2. Pingback: Build a 2D Top Down Game - Zero to Published - Dave Crook's Dev Blog - Site Home - MSDN Blogs

  3. both the CharacterScript and the HeroScript have the SetDeathFunction lambda. I am getting :

    ‘CharacterScript’ does not contain a definition for ‘SetDeathFunction’ and no extention blah blah blah.

    I have reread over the previous tutorials and the compiler is right. You haven’t declared a ‘SetDeathFunction’ anywhere in the CharacterScript.

    Could you or anyone shed any light on this? Did you miss something out?

Leave a Reply

Your email address will not be published. Required fields are marked *