文章来源:https://www.toymoban.com/news/detail-506356.html
文章来源地址https://www.toymoban.com/news/detail-506356.html
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UIFollow3DObj : MonoBehaviour
{
[Header("跟随的物体")]
public Transform targetTran;
[Header("偏移值")]
public Vector2 Offset;
/// <summary>
///
/// </summary>
RectTransform canvasTran, uiTran;
void Start()
{
uiTran = transform.GetComponent<RectTransform>();
canvasTran = transform.GetComponentInParent<Canvas>().GetComponent<RectTransform>();
}
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<Canvas>().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;
}
}
到了这里,关于unity UI 跟随3D物体移动的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!