2D Healthbar help (Healthbar rotates with enemy)

I am working on a 2d game where the player runs around shooting and enemies attack. I created the project in 2D but I had the enemies rotate towards the player when attacking. I have a healthbar that works but it rotates with the enemies so if the enemy is above you coming down from the top of the screen its healthbar appears under it. Is there a way to always have the healthbar at the top of the enemy no matter which direction the enemy is facing?

Here is my current enemyhealth script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyHealth : MonoBehaviour
{
    public float MaxHealth = 100;
    public float currentHealth;
    public GameObject healthbar;

    public void Start()
    {
        currentHealth = MaxHealth;
    }

    public void TakeDamage(float damage)
    {
        currentHealth -= damage;
        if (currentHealth <= 0)
        {
            Die();
        }
        healthbar.transform.localScale = new Vector3(currentHealth / 100, healthbar.transform.localScale.y, healthbar.transform.localScale.z);
    }

    void Die()
    {
        healthbar.SetActive(false);
    }
}

And here is my healthbar code:

public class HealthBar : MonoBehaviour {

    Vector3 localScale;
    public EnemyHealth enemyHealth;

    // Use this for initialization
    void Start () {
        localScale = transform.localScale;
    }
   
    // Update is called once per frame
    void Update () {

        localScale.x = enemyHealth.currentHealth;
        transform.localScale = localScale;
    }
}

One way is to reparent your prefabs so you have a base that does not rotate, then two branches of hierarchy below it:

  • one that also does not rotate where you put the health bar

  • the visuals that do rotate

Another way is to have the healthbar be a separate entity that is not parented to the entity but rather takes a position only from it, not a rotation, copying the target entity position each frame, perhaps in LateUpdate(), or else as an explicit post-move call from the entity.

One can do this by creating a new Canvas, changing the RenderMode to WorldSpace, and then parenting the Canvas to your object. No code needed.

1 Like

Thanks for the ideas mates. I will give them a go this week and see if I can solve this issue.

1 Like