在Canvas不同渲染模式(RenderMode)下实现UI跟随3D物体功能。
Screen Space-Overlay
利用WorldToScreenPoint()将物体的世界坐标转换成屏幕坐标,然后更新UI的坐标:
1.UI跟随3D物体
public class UIFollowObj : MonoBehaviour {
public GameObject obj;//3D物体
public RectTransform rectUI;//UI元素
public Vector2 offset;//偏移量
void Start(){
offset = new Vector3(0, 0, 0);
}
void Update () {
Vector2 screenPos=Camera.main.WorldToScreenPoint(obj.transform.position);
rectUI.position = screenPos + offset;
}
}
2.UI跟随鼠标
public Vector3 offset;
void Update()
{
gameObject.transform.position = Input.mousePosition+ offset;
}
Screen Space-Camera
RectTransformUtility.ScreenPointToLocalPointInRectangle换算出UI元素在Canvas的2D坐标:
1.UI跟随3d物体
public Camera UI_Camera;//UI相机
public RectTransform image;//UI元素
public Canvas ui_Canvas;
void UpdateUIPosition()
{
Vector2 PlayerScreen = Camera.main.WorldToScreenPoint(Player.transform.position);
Vector2 mouseUGUIPos = new Vector2();
bool isRect = RectTransformUtility.ScreenPointToLocalPointInRectangle(ui_Canvas.transform as RectTransform, PlayerScreen, UI_Camera, out mouseUGUIPos);
Debug.Log(mouseUGUIPos);
if (isRect)
{
image.anchoredPosition = mouseUGUIPos;
}
}
2.UI跟随鼠标(此处我的分辨率是1920*1080)
//Canvas
public RectTransform canvasRectTra;
//需要跟随的UI
public RectTransform imageRectTra;
//UI相机
public Camera mainCamera;
void Update()
{
SetImagePosition(Input.mousePosition+new Vector3(1920/2,1080/2,0));
}
/// <summary>
/// 参数为鼠标点击坐标
/// </summary>
/// <param name="v3"></param>
private void SetImagePosition(Vector3 v3)
{
Vector2 imagePanelV2 = new Vector2();
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasRectTra, v3, mainCamera, out imagePanelV2))
{
imageRectTra.anchoredPosition = imagePanelV2;
}
}