using UnityEngine;
public class LabelFollow3DObject : MonoBehaviour
{
/// <summary>
/// 2D标签跟随对象
/// </summary>
public Transform targetObj;
/// <summary>
/// 2D平面标签对象
/// </summary>
public GameObject labelObj;
void Update()
{
UpdateLabel(targetObj);
}
/// <summary>
/// 更新标签位置
/// </summary>
/// <param name="target"></param>
void UpdateLabel(Transform target)
{
RectTransform labelRt = labelObj.GetComponent<RectTransform>();
if (Camera.main == null) return;
Vector3 screenPos = Camera.main.WorldToScreenPoint(target.position);
RectTransform rect = GameObject.Find("Canvas").GetComponent<RectTransform>();
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(rect, screenPos, null, out Vector2 outVec))
{
outVec += new Vector2(0, -GameObject.Find("Canvas").transform.Find("LabelContent").localPosition.y);
}
labelRt.anchoredPosition = outVec;
}
}
Unity 2D标签跟随3D物体移动
于 2024-01-03 11:04:15 首次发布