Quantcast
Channel: Latest Questions on Unity Answers
Viewing all articles
Browse latest Browse all 171066

What is wrong with this code ?

$
0
0
Hereunder is he health bar code I have for my units (a green bar floating above the units - RTS style). The problem is that the bar does not stick to the unit (or move together with it). In the second i move the camera the health bar moves in that direction. Can you please help ? using UnityEngine; using System.Collections; public class AIHealth : MonoBehaviour { public int maxHp; public int currentHp; public Camera mainCamera; public Texture2D hpBarBG; public Texture2D hpBarCurrent; public Transform target; 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-2; Debug.Log(offsetY); } void Update () { health h=(health)GetComponent("health"); h.currenthealth = currentHp; h.maxhealth = maxHp; var wantedPos = Camera.main.WorldToViewportPoint (target.position); transform.position = wantedPos; } 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); } }

Viewing all articles
Browse latest Browse all 171066

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>