unity实现UI元素跟随3D物体
本文实例为大家分享了unity实现UI元素跟随3D物体的具体代码,供大家参考,具体内容如下
在Canvas不同的渲染模式(RenderMode)下实现UI跟随3D物体
当Canvas.RenderMode为Screen Space-Overlay时
利用WorldToScreenPoint(worldPos)将物体的世界坐标转换成屏幕坐标,实时更新UI的坐标:
```csharp
using UnityEngine;
using System.Collections;
public class FollowWorldObj : MonoBehaviour {
[SerializeField]
GameObject worldPos;//3D物体(人物)
[SerializeField]
RectTransform rectTrans;//UI元素(如:血条等)
public Vector2 offset;//偏移量
// Update is called once per frame
void Update () {
Vector2 screenPos=Camera.main.WorldToScreenPoint(worldPos.transform.position);
rectTrans.position = screenPos + offset;
}
}
当Canvas.RenderMode为Screen Space-Camera时
利用RectTransformUtility.ScreenPointToLocalPointInRectangle换算出UI元素在Canvas的2D坐标:
using UnityEngine;
using System.Collection