Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using UnityEngine;
- using System.Collections;
- using UnityEngine.UI;
- public class Health : MonoBehaviour
- {
- public Image health;
- public bool isMainChar;
- public float currentHealth, maxHealth;
- private CapsuleCollider capsule;
- private Vector3 constPos;
- void Awake()
- {
- health = (Instantiate(Resources.Load("healthPref")) as GameObject).GetComponent<Image>();
- health.transform.SetParent(GameObject.Find("Canvas").transform);
- health.rectTransform.localScale=new Vector3(1,1,1);
- constPos=new Vector3(20*1.5f+health.rectTransform.rect.width/2f, Screen.height-(40+health.rectTransform.rect.height), 0);
- }
- void Start ()
- {
- health.fillAmount = 1;
- health.color = Color.green;
- capsule = GetComponent<CapsuleCollider>();
- }
- // Update is called once per frame
- void Update ()
- {
- health.fillAmount = (1/maxHealth)*currentHealth;
- health.color = Color.Lerp(Color.red, Color.green, health.fillAmount);
- if(!isMainChar)
- if (Vector3.Dot(Camera.main.transform.forward, (transform.position - Camera.main.transform.position)) < 1f)
- {
- health.enabled = false;
- }
- else
- {
- health.enabled = true;
- }
- }
- void LateUpdate()
- {
- if (!isMainChar)
- {
- Vector3 pos2d = transform.position;
- pos2d.y += (capsule.height/2f+capsule.center.y);
- pos2d = Camera.main.WorldToScreenPoint(pos2d);
- pos2d.y += 10;
- health.rectTransform.position = pos2d;
- }
- else
- {
- health.rectTransform.position = constPos;
- }
- }
- public void SetHealth(float current, float max)
- {
- currentHealth = current;
- maxHealth = max;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement