欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

UGUI--------UI以及3D物体显示在鼠标点击位置

程序员文章站 2022-03-26 16:09:27
...

1、鼠标的点击的位置—赋值给3D物体

 float distance=5;
    /// <summary>
    /// 赋值鼠标位置给3D物体
    /// </summary>
    void MouseTo3DPos()
    {
        Vector2 mousePosition = Input.mousePosition;
        Vector3 targetPosition = Camera.main.ScreenToWorldPoint(new Vector3(mousePosition.x, mousePosition.y, distance));
        cube.position = targetPosition;
    }

2、鼠标的点击位置—赋值给UI物体
2.1、当UI的Canvas的RenderMode为Screen Space–Overlay

  public Text m_text;
    void MouseToUI()
    {
        Vector3 mousePosition = Input.mousePosition;
        m_text.transform.position = mousePosition;
    }

2.2、当UI的Canvas的RenderMode为World Space,其中m_text.transform .parent为该Text所在Canvas.

 void MouseToUI()
    {
        Vector2 localPoint;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(m_text.transform .parent .GetComponent <RectTransform >(), Input.mousePosition, Camera.main , out localPoint);
        m_text.transform.localPosition = localPoint;

    }