unity实现UI元素跟随3D物体
作者:夸克电子浆 时间:2021-11-15 02:00:48
本文实例为大家分享了unity实现UI元素跟随3D物体的具体代码,供大家参考,具体内容如下
在Canvas不同的渲染模式(RenderMode)下实现UI跟随3D物体
当Canvas.RenderMode为Screen Space-Overlay时
利用WorldToScreenPoint(worldPos)将物体的世界坐标转换成屏幕坐标,实时更新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;
}
}
}
效果如下:
来源:https://blog.csdn.net/nnew_hande/article/details/78501309
标签:unity,跟随,3D物体
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
通过实例解析JMM和Volatile底层原理
2023-05-20 19:10:48
![](https://img.aspxhome.com/file/2023/1/62201_0s.png)
SpringBoot使用jsr303校验的实现
2022-04-21 04:02:39
C#窗体实现酒店管理系统
2023-05-23 18:58:47
![](https://img.aspxhome.com/file/2023/5/79125_0s.jpg)
java操作excel表格详解
2021-08-20 14:35:46
![](https://img.aspxhome.com/file/2023/9/76269_0s.png)
SpringBoot集成EasyExcel的步骤
2023-07-19 09:59:17
springboot配置https访问的方法
2022-12-11 16:17:37
详解Java对象的强、软、弱和虚引用+ReferenceQueue
2021-11-30 16:23:01
C#中XML基础用法
2023-08-05 17:12:34
Spring JPA学习之delete方法示例详解
2021-11-23 12:22:55
![](https://img.aspxhome.com/file/2023/8/67108_0s.webp)
JAVA反射机制实例教程
2023-11-25 23:33:47
IntelliJ IDEA本地代码提交到github网站不显示与本地不同步问题的解决办法
2022-09-21 10:50:44
![](https://img.aspxhome.com/file/2023/2/93342_0s.png)
Java OpenCV4.0.0实现实时人脸识别
2023-11-16 07:29:14
![](https://img.aspxhome.com/file/2023/9/61779_0s.jpg)
详解Spring Bean 之间的特殊关系
2022-10-25 21:12:17
Android中解决WebView上下滑动监听问题
2022-04-18 04:45:37
C#中WebClient实现文件下载
2022-10-11 18:04:57
![](https://img.aspxhome.com/file/2023/5/77275_0s.png)
Spring事务传播中嵌套调用实现方法详细介绍
2021-08-31 22:34:24
![](https://img.aspxhome.com/file/2023/3/69733_0s.png)
c# socket编程udp客户端实现代码分享
2023-06-16 05:03:31
探讨Java中的深浅拷贝问题
2023-01-07 01:12:44
![](https://img.aspxhome.com/file/2023/7/72547_0s.jpg)
Spring Data JPA 复杂/多条件组合分页查询
2021-09-06 02:57:55
Java文件读写IO/NIO及性能比较详细代码及总结
2021-11-28 12:56:30