unity實現(xiàn)UI元素跟隨3D物體
本文實例為大家分享了unity實現(xiàn)UI元素跟隨3D物體的具體代碼,供大家參考,具體內(nèi)容如下
在Canvas不同的渲染模式(RenderMode)下實現(xiàn)UI跟隨3D物體
當Canvas.RenderMode為Screen Space-Overlay時
利用WorldToScreenPoint(worldPos)將物體的世界坐標轉(zhuǎn)換成屏幕坐標,實時更新UI的坐標:
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.Collections;
using UnityEngine.EventSystems;
public class UI_FollowObj : MonoBehaviour {
[SerializeField]
Camera UI_Camera;//UI相機
[SerializeField]
RectTransform image;//UI元素
[SerializeField]
GameObject obj;//3D物體
[SerializeField]
Canvas ui_Canvas;
// Update is called once per frame
void Update () {
UpdateNamePosition();
}
/// <summary>
/// 更新image位置
/// </summary>
void UpdateNamePosition()
{
Vector2 mouseDown = Camera.main.WorldToScreenPoint(obj.transform.position);
Vector2 mouseUGUIPos = new Vector2();
bool isRect = RectTransformUtility.ScreenPointToLocalPointInRectangle(ui_Canvas.transform as RectTransform, mouseDown, UI_Camera, out mouseUGUIPos);
if (isRect)
{
image.anchoredPosition = mouseUGUIPos;
}
}
}
效果如下:

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
基于C#?實現(xiàn)劉謙春晚魔術(shù)(示例代碼)
劉謙春晚魔術(shù)是一個讓人嘆為觀止的魔術(shù)表演,其中涉及到了數(shù)學、編程和創(chuàng)意的結(jié)合,看了春晚魔術(shù)的朋友們,是不是好奇春晚劉謙的魔術(shù)是怎么變的,本文分享C#?實現(xiàn)劉謙春晚魔術(shù)示例代碼,一起看看吧2024-02-02

