当前位置:   article > 正文

Unity Canvas不同模式下实现UI追随物体_unity ui跟随物体

unity ui跟随物体

在Canvas不同渲染模式(RenderMode)下实现UI跟随3D物体功能。

Screen Space-Overlay

利用WorldToScreenPoint()将物体的世界坐标转换成屏幕坐标,然后更新UI的坐标:

1.UI跟随3D物体

  1. public class UIFollowObj : MonoBehaviour {
  2. public GameObject obj;//3D物体
  3. public RectTransform rectUI;//UI元素
  4. public Vector2 offset;//偏移量
  5. void Start(){
  6. offset = new Vector3(0, 0, 0);
  7. }
  8. void Update () {
  9. Vector2 screenPos=Camera.main.WorldToScreenPoint(obj.transform.position);
  10. rectUI.position = screenPos + offset;
  11. }
  12. }

2.UI跟随鼠标

  1. public Vector3 offset;
  2. void Update()
  3. {
  4. gameObject.transform.position = Input.mousePosition+ offset;
  5. }

Screen Space-Camera

RectTransformUtility.ScreenPointToLocalPointInRectangle换算出UI元素在Canvas的2D坐标:

1.UI跟随3d物体

  1. public Camera UI_Camera;//UI相机
  2. public RectTransform image;//UI元素
  3. public Canvas ui_Canvas;
  4. void UpdateUIPosition()
  5. {
  6. Vector2 PlayerScreen = Camera.main.WorldToScreenPoint(Player.transform.position);
  7. Vector2 mouseUGUIPos = new Vector2();
  8. bool isRect = RectTransformUtility.ScreenPointToLocalPointInRectangle(ui_Canvas.transform as RectTransform, PlayerScreen, UI_Camera, out mouseUGUIPos);
  9. Debug.Log(mouseUGUIPos);
  10. if (isRect)
  11. {
  12. image.anchoredPosition = mouseUGUIPos;
  13. }
  14. }

2.UI跟随鼠标(此处我的分辨率是1920*1080)

  1. //Canvas
  2. public RectTransform canvasRectTra;
  3. //需要跟随的UI
  4. public RectTransform imageRectTra;
  5. //UI相机
  6. public Camera mainCamera;
  7. void Update()
  8. {
  9. SetImagePosition(Input.mousePosition+new Vector3(1920/2,1080/2,0));
  10. }
  11. /// <summary>
  12. /// 参数为鼠标点击坐标
  13. /// </summary>
  14. /// <param name="v3"></param>
  15. private void SetImagePosition(Vector3 v3)
  16. {
  17. Vector2 imagePanelV2 = new Vector2();
  18. if (RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasRectTra, v3, mainCamera, out imagePanelV2))
  19. {
  20. imageRectTra.anchoredPosition = imagePanelV2;
  21. }
  22. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/111377
推荐阅读
相关标签
  

闽ICP备14008679号