Unity中UI跟随3D物体即HUD效果
今天简单的测试了Unity中UI跟随3D物体,使⽤Unity版本:5.6.4。
⾸先想到的有两种思路:
1、第⼀种⽅法基于RectTransformUtility.ScreenPointToWorldPointInRectangle和 Camera.main.WorldToScreenPoint这两个⽅法
⾸先把3D物体坐标转换到屏幕坐标,然后在从屏幕坐标转换到UI坐标:
public Transform target; //3D物体
public RectTransform image; //跟随3D物体的UI
public Canvas canvas; //UI所在的canvas
private Vector2 screenPos;
private Vector3 mouPos;
void Update()
{札幌大学
screenPos = Camera.main.WorldToScreenPoint(target.position);
大绶if (RectTransformUtility.ScreenPointToWorldPointInRectangle(image, screenPos, canvas.worldCamera, out mouPos)) {
image.position = mouPos;
丝羽乌骨鸡}
}
香菜饺子此时 UI就实现了3D物体。
2、当我们实现了第⼀个⽅法,此时在想我们基于Camera.main.WorldToScreenPoint⽅法,获取到屏幕坐标,然后根据屏幕坐标和UI坐标不同计算出UI坐标。
屏幕空间以像素定义,屏幕左下为0,0,UI坐标0,0点在屏幕正中间,如果加上x和y轴偏移量,我们可以使⽤⼀下⽅法实现:
public RectTransform rectBloodPos;
public int offsteX = 0;
public int offtY = 60;
新妈妈2017private Vector2 screenPoint;
private Vector2 currPos = new Vector2();
void Update()
{
screenPoint = Camera.main.WorldToScreenPoint(ansform.position);
currPos.x = screenPoint.x - Screen.width / 2 + offsteX;
currPos.y = screenPoint.y - Screen.height / 2 + offtY;
rectBloodPos.anchoredPosition = currPos;//控制偏移量
巧克力的图片}搞笑的头像
二十四个韵母次⽅法也实现了HUD效果。