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)文章
Unity實(shí)現(xiàn)簡(jiǎn)單場(chǎng)景分層移動(dòng)
這篇文章主要為大家詳細(xì)介紹了Unity實(shí)現(xiàn)簡(jiǎn)單場(chǎng)景分層移動(dòng),分為前景、場(chǎng)景、背景等,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09
基于C#?實(shí)現(xiàn)劉謙春晚魔術(shù)(示例代碼)
劉謙春晚魔術(shù)是一個(gè)讓人嘆為觀止的魔術(shù)表演,其中涉及到了數(shù)學(xué)、編程和創(chuàng)意的結(jié)合,看了春晚魔術(shù)的朋友們,是不是好奇春晚劉謙的魔術(shù)是怎么變的,本文分享C#?實(shí)現(xiàn)劉謙春晚魔術(shù)示例代碼,一起看看吧2024-02-02
C#中動(dòng)態(tài)顯示當(dāng)前系統(tǒng)時(shí)間的實(shí)例方法
想在網(wǎng)頁(yè)中動(dòng)態(tài)地顯示當(dāng)前系統(tǒng)的時(shí)間,找了好多,不過(guò)都是一些停在那里不動(dòng)的。。。不過(guò)皇天不負(fù)有心人,終于讓我找到了2013-05-05

