赞
踩
在Canvas不同渲染模式(RenderMode)下实现UI跟随3D物体功能。
利用WorldToScreenPoint()将物体的世界坐标转换成屏幕坐标,然后更新UI的坐标:
- public class UIFollowObj : MonoBehaviour {
-
- public GameObject obj;//3D物体
-
- public RectTransform rectUI;//UI元素
-
- public Vector2 offset;//偏移量
-
- void Start(){
-
- offset = new Vector3(0, 0, 0);
- }
- void Update () {
- Vector2 screenPos=Camera.main.WorldToScreenPoint(obj.transform.position);
- rectUI.position = screenPos + offset;
- }
- }
- public Vector3 offset;
-
- void Update()
- {
- gameObject.transform.position = Input.mousePosition+ offset;
- }
RectTransformUtility.ScreenPointToLocalPointInRectangle换算出UI元素在Canvas的2D坐标:
- public Camera UI_Camera;//UI相机
- public RectTransform image;//UI元素
- public Canvas ui_Canvas;
- void UpdateUIPosition()
- {
- Vector2 PlayerScreen = Camera.main.WorldToScreenPoint(Player.transform.position);
- Vector2 mouseUGUIPos = new Vector2();
- bool isRect = RectTransformUtility.ScreenPointToLocalPointInRectangle(ui_Canvas.transform as RectTransform, PlayerScreen, UI_Camera, out mouseUGUIPos);
-
- Debug.Log(mouseUGUIPos);
- if (isRect)
- {
- image.anchoredPosition = mouseUGUIPos;
- }
- }
2.UI跟随鼠标(此处我的分辨率是1920*1080)
- //Canvas
- public RectTransform canvasRectTra;
- //需要跟随的UI
- public RectTransform imageRectTra;
- //UI相机
- public Camera mainCamera;
-
-
- void Update()
- {
- SetImagePosition(Input.mousePosition+new Vector3(1920/2,1080/2,0));
- }
-
- /// <summary>
- /// 参数为鼠标点击坐标
- /// </summary>
- /// <param name="v3"></param>
- private void SetImagePosition(Vector3 v3)
- {
- Vector2 imagePanelV2 = new Vector2();
-
- if (RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasRectTra, v3, mainCamera, out imagePanelV2))
- {
-
- imageRectTra.anchoredPosition = imagePanelV2;
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。