Unity UGUI HUD怪物血条实现

发表于2017-05-03
评论2 7.6k浏览
  大多数游戏怪物都有血条,受到攻击时怪物血量还会减少,那么这个怪物血条功能是怎么实现的呢,下面就给大家介绍下UGUI HUD怪物血条的实现方法。

  首先做一个血条,创建一个名为Follow3DObject的脚本添加到血条控件上。

  Follow3DObject.cs的代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using UnityEngine;
using System.Collections;
 
public class Follow3DObject : MonoBehaviour
{
 
    public Transform target;
    public Vector3 offset = new Vector3(0, 1, 0);
 
    // Use this for initialization
    void Start()
    {
 
    }
 
    // Update is called once per frame
    void Update()
    {
        if (target != null)
        {
            transform.position = Camera.main.WorldToScreenPoint(target.position + offset);
        }
    }
}

  将上面的脚本的target设置成对应的怪物,就可以看到血条跟着怪物移动了。

  再给一个血条排序的脚本,这里是简单的根据Z轴的坐标来对血条进行排序的。实际场景下可能需要根据摄像机看到的怪物的顺序来进行排序,只要替换一下排序算法就行了。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
using UnityEngine;
using System.Collections;
using Boo.Lang;
 
public class SortHUD : MonoBehaviour
{
 
    // Use this for initialization
    void Start()
    {
 
    }
 
    // Update is called once per frame
    void Update()
    {
        var list = new List();
        foreach (Transform t in transform)
        {
            list.Add(t);
        }
 
        list.Sort((a, b) =>
        {
            return a.position.z.CompareTo(b.position.z);
        });
 
        for (int i = 0; i < list.Count; i++)
        {
            list[i].SetSiblingIndex(i);
        }
    }
}

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引