【Unity3D——UIFixedObj】用于跟随物体显示UI标签(如角色名、血条等)

该脚本用于跟随物体显示UI标签(如角色名、血条等)。

跟随角色,显示角色名或者血条/蓝条等,且不受摄像机距离远近影响。

可扩展:使该UI未处于视野范围内时隐藏,处于视野范围内时显示。

效果图如下所示:

代码如下所示:

using UnityEngine;
using UnityEngine.UI;

/// <summary>
/// 此脚本用于跟随物体显示UI标签(如角色名、血条等)
/// 挂载到UI上即可
/// </summary>
public class UIFixedObj : MonoBehaviour
{
    public GameObject obj;    //跟随目标对象
    private RectTransform rect;
    private float scalerX;
    private float scalerY;
    // Use this for initialization
    void Start ()
    {
        rect = (RectTransform)transform;
        CanvasScaler scaler = transform.root.GetComponent<CanvasScaler>();
        scalerX = scaler.referenceResolution.x;
        scalerY = scaler.referenceResolution.y;
    }

    void Update()
    {
        Vector2 pos;
        Canvas canvas = transform.root.GetComponent<Canvas>();
        if (Camera.main == null) return;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.transform as RectTransform,
            Camera.main.WorldToScreenPoint(obj.transform.position), canvas.worldCamera, out pos);
        {
            //此处限制在Game视图内部
            if (pos.x + rect.rect.width > scalerX / 2)
                pos = new Vector2(scalerX / 2 - rect.rect.width, pos.y);
            if (pos.x < -scalerX / 2)
                pos = new Vector2(-scalerX / 2, pos.y);
            if (pos.y > scalerY / 2)
                pos = new Vector2(pos.x, scalerY / 2);
            if (pos.y - rect.rect.height < -scalerY / 2)
                pos = new Vector2(pos.x, -scalerY / 2 + rect.rect.height);
            rect.localPosition = pos;
        }
    }
}

如转载请注明出处:IT_yanghui【Unity3D——UIFixedObj】用于跟随物体显示UI标签(如角色名、血条等)

  • 4
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值