Created
October 11, 2014 01:10
-
-
Save abdullah353/2855be7c9fe14445584e to your computer and use it in GitHub Desktop.
From http://answers.unity3d.com/questions/403697/rts-healthbar-gui-box-follow-gameobject-with-persp.html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using UnityEngine;using System.Collections; public class Attackable : MonoBehaviour { public float maxHp; public float currentHp; public Camera mainCamera; public Texture2D hpBarBG; public Texture2D hpBarCurrent; private float offsetY; //script will be atached to each GameObject that can suffer dmg. void Start () { //put it on top of the character offsetY=gameObject.collider.bounds.size.y+5; Debug.Log(offsetY); } void Update () { } void OnGUI(){ //the hp bar background location on screen Rect rcBg = new Rect(0,0,60,14); //the current HP bar Rect rcCurrent = new Rect(0,0,((currentHp)/maxHp)*56,8); //the important part : where this object is located in my screen Vector3 point = mainCamera.WorldToScreenPoint(new Vector3( transform.position.x, transform.position.y+offsetY, transform.position.z) ); //had to add the substraction since my Y axis were revesed ( rcBg.y = Screen.height-point.y; //do some ugly hardcoding so the bar is pretty and centered rcBg.x = point.x-30; rcCurrent.x=rcBg.x+2; rcCurrent.y=rcBg.y+3; GUI.DrawTexture(rcBg,hpBarBG); GUI.DrawTexture(rcCurrent,hpBarCurrent); } } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment