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

文章介绍了如何在Unity中,根据不同Canvas渲染模式(ScreenSpace-Overlay和ScreenSpace-Camera)实现UI元素跟随3D物体或鼠标的技巧。通过WorldToScreenPoint函数转换坐标以及RectTransform组件更新UI位置,确保UI元素动态匹配3D场景中的目标对象。
摘要由CSDN通过智能技术生成

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

Screen Space-Overlay

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

1.UI跟随3D物体

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;
 }
}

2.UI跟随鼠标

    public Vector3 offset;
 
    void Update()
    {
     gameObject.transform.position = Input.mousePosition+ offset;
    }

Screen Space-Camera

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

1.UI跟随3d物体

    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;
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值