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)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
基于不要返回null之EmptyFactory的應(yīng)用詳解
本篇文章對不要返回null之EmptyFactory進行了詳細的分析介紹,需要的朋友參考下2013-05-05C#中實現(xiàn)線程同步lock關(guān)鍵字的用法詳解
實現(xiàn)線程同步的第一種方式是我們經(jīng)常使用的lock關(guān)鍵字,它將包圍的語句塊標記為臨界區(qū),這樣一次只有一個線程進入臨界區(qū)并執(zhí)行代碼,接下來通過本文給大家介紹C#中實現(xiàn)線程同步lock關(guān)鍵字的用法詳解,一起看看吧2016-07-07C#中關(guān)于double.ToString()的用法
這篇文章主要介紹了C#中關(guān)于double.ToString()的用法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02