Advertisement
Guest User

Untitled

a guest
May 28th, 2015
354
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.80 KB | None | 0 0
  1. using System;
  2. using UnityEngine;
  3. using System.Collections;
  4. using UnityEngine.UI;
  5.  
  6. public class Health : MonoBehaviour
  7. {
  8.     public Image health;
  9.     public bool isMainChar;
  10.     public float currentHealth, maxHealth;
  11.     private CapsuleCollider capsule;
  12.     private Vector3 constPos;
  13.  
  14.     void Awake()
  15.     {
  16.         health = (Instantiate(Resources.Load("healthPref")) as GameObject).GetComponent<Image>();
  17.         health.transform.SetParent(GameObject.Find("Canvas").transform);
  18.         health.rectTransform.localScale=new Vector3(1,1,1);
  19.         constPos=new Vector3(20*1.5f+health.rectTransform.rect.width/2f, Screen.height-(40+health.rectTransform.rect.height), 0);
  20.     }
  21.  
  22.     void Start ()
  23.     {
  24.         health.fillAmount = 1;
  25.         health.color = Color.green;
  26.         capsule = GetComponent<CapsuleCollider>();
  27.     }
  28.    
  29.     // Update is called once per frame
  30.     void Update ()
  31.     {
  32.         health.fillAmount = (1/maxHealth)*currentHealth;
  33.         health.color = Color.Lerp(Color.red, Color.green, health.fillAmount);
  34.  
  35.         if(!isMainChar)
  36.         if (Vector3.Dot(Camera.main.transform.forward, (transform.position - Camera.main.transform.position)) < 1f)
  37.         {
  38.             health.enabled = false;
  39.         }
  40.         else
  41.         {
  42.             health.enabled = true;
  43.         }
  44.     }
  45.  
  46.     void LateUpdate()
  47.     {
  48.         if (!isMainChar)
  49.         {
  50.             Vector3 pos2d = transform.position;
  51.             pos2d.y += (capsule.height/2f+capsule.center.y);
  52.  
  53.             pos2d = Camera.main.WorldToScreenPoint(pos2d);
  54.             pos2d.y += 10;
  55.             health.rectTransform.position = pos2d;
  56.         }
  57.         else
  58.         {
  59.             health.rectTransform.position = constPos;
  60.         }
  61.     }
  62.  
  63.     public void SetHealth(float current, float max)
  64.     {
  65.         currentHealth = current;
  66.         maxHealth = max;
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement