unity實(shí)現(xiàn)UI元素跟隨3D物體
本文實(shí)例為大家分享了unity實(shí)現(xiàn)UI元素跟隨3D物體的具體代碼,供大家參考,具體內(nèi)容如下
在Canvas不同的渲染模式(RenderMode)下實(shí)現(xiàn)UI跟隨3D物體
當(dāng)Canvas.RenderMode為Screen Space-Overlay時(shí)
利用WorldToScreenPoint(worldPos)將物體的世界坐標(biāo)轉(zhuǎn)換成屏幕坐標(biāo),實(shí)時(shí)更新UI的坐標(biāo):
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;
}
}
當(dāng)Canvas.RenderMode為Screen Space-Camera時(shí)
利用RectTransformUtility.ScreenPointToLocalPointInRectangle換算出UI元素在Canvas的2D坐標(biāo):
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class UI_FollowObj : MonoBehaviour {
[SerializeField]
Camera UI_Camera;//UI相機(jī)
[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;
}
}
}
效果如下:

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

