unity UI 跟随3D物体移动

unity UI 跟随3D物体移动_第1张图片

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UIFollow3DObj : MonoBehaviour
{
    [Header("跟随的物体")]
    public Transform targetTran;

    [Header("偏移值")]
    public Vector2 Offset;

    /// 
    /// 
    /// 
    RectTransform canvasTran, uiTran;

    void Start()
    {
        uiTran = transform.GetComponent();
        canvasTran = transform.GetComponentInParent().GetComponent();
    }

    private void Update()
    {
        if (targetTran != null)
        {
            if (isInFront())
            {
                Vector2 mScreenPos = Camera.main.WorldToScreenPoint(targetTran.transform.position);
                Vector2 mRectPos;
                RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasTran, mScreenPos, null, out mRectPos);
                uiTran.anchoredPosition = mRectPos + Offset;
                uiTran.localScale = Vector3.one;
            }
            else
            {
                uiTran.localScale = Vector3.zero;
            }


            //Vector2 mScreenPos = Camera.main.WorldToScreenPoint(targetTran.transform.position);
            //if (RectTransformUtility.ScreenPointToLocalPointInRectangle(uiTran.root.transform as RectTransform,
            // Camera.main.WorldToScreenPoint(targetTran.position), uiTran.root.GetComponent().worldCamera, out mScreenPos))
            //{
            //    uiTran.anchoredPosition = mScreenPos + Offset;

            //    //血条超出屏幕就不显示  
            //    if (mScreenPos.x > Screen.width / 2 || mScreenPos.x < -Screen.width / 2 || mScreenPos.y > Screen.height / 2 || mScreenPos.y < -Screen.height / 2)
            //    {
            //        uiTran.gameObject.SetActive(false);
            //    }
            //    else
            //    {
            //        uiTran.gameObject.SetActive(true);
            //    }
            //}
        }
    }

    //判定在摄像头前面
    public bool isInFront()
    {     
        Vector3 dir = (targetTran.position - Camera.main.transform.position).normalized;
        float dot = Vector3.Dot(Camera.main.transform.forward, dir);
        if (dot > 0)
            return true;
        else
            return false;
    }

}

你可能感兴趣的:(Ugui,unity,ui,3d)