Trying to keep my health bar horizontally fixed above the enemy or player even if the enemy or player rotates
Asked Answered
I

2

0

Health Bar issue: https://i.gyazo.com/cfa5ee306193bdea7649821ea1b63933.gif
I was trying to make this script so the health bar would always stay horizontal and above the GameObject (player or enemy) no matter how they rotated but its still not working any ideas?

Health Bar Script:

using UnityEngine;
using UnityEngine.UI;

public class StatusIndicator : MonoBehaviour {

	[SerializeField]
	private RectTransform healthBarRect;
	[SerializeField]
	//private Text healthText;
	private GameObject gameObject;

	void Start()
	{
		if (healthBarRect == null) 
		{	
			Debug.LogError ("StatusIndicator Bar is Missing");
		}

		//if (healthText == null) 
		//{	
			//Debug.LogError("StatusIndicator Bar is Missing");
		//}
	}

	void Update ()
	{
		healthBarRect.transform.position.Set(gameObject.transform.position.x, gameObject.transform.position.y+0.5f, gameObject.transform.position.z);
	}

	public void SetHealth(int _cur, int _max)
	{
		float _value = (float)_cur / _max;

		healthBarRect.localScale = new Vector3(_value, healthBarRect.localScale.y, healthBarRect.localScale.z);
		//healthText.text = _cur + "/" + _max + "HP";
	}

}
Immaterialize answered 2/8, 2016 at 0:12 Comment(0)
T
0

What if you made the healthbar a child, and only rotated the parent’s sprite? Something along those lines… prevent the bar from rotating by rotating the parent (or child, depending on how you set it up).

Taw answered 2/8, 2016 at 11:58 Comment(0)
C
0

I know I’m very late, but to anyone else looking I’ve just made a very simple script to attatch to the health bar, setting it’s rotation and location each frame.

public class PositionHealthBar : MonoBehaviour
{
    public GameObject enemy;
    public float healthBarOffset;

    // Update is called once per frame
    void Update()
    {
        transform.eulerAngles = new Vector3(0, 0, 0);
        transform.position = new Vector3(enemy.transform.position.x, enemy.transform.position.y + healthBarOffset, 0);
    }
}
Culbertson answered 6/7 at 0:39 Comment(1)

i love you

Derayne

© 2022 - 2024 — McMap. All rights reserved.