【问题标题】:Converting from Pixel Coordinates to UI Coordinates in Unity在 Unity 中从像素坐标转换为 UI 坐标
【发布时间】:2015-06-17 18:40:19
【问题描述】:

有谁知道如何在 Unity 中将像素坐标转换为 UI 坐标,反之亦然?例如,假设我想用鼠标单击屏幕上的某个位置,并且 UI 图像位于该单击位置。如果我这样做是行不通的:

Image img = null // I assign it via the inspector
void Update()
{
    if(Input.GetMouseButtonDown(0))
    {
        img.rectTransform.anchorPosition = Input.mousePosition;
    }
}

【问题讨论】:

    标签: user-interface unity3d


    【解决方案1】:
    Image img = null // I assign it via the inspector
    void Update()
    {
    
            if(Input.GetMouseButtonDown(0))
        {
            Vector2 point;
            RectTransformUtility.ScreenPointToLocalPointInRectangle((RectTransform)img.rectTransform.parent, Input.mousePosition, canvasCamera, out point);
            img.rectTransform.anchorPosition = point;
        }
    }
    

    【讨论】:

    • 完美。有效。谢谢你。对于那些有这个问题的人,附加信息:ui 元素的画布必须处于屏幕空间相机模式。同样作为 ScreenPointToLocalPointInRectangle 函数的第三个参数,使用画布使用的相机。
    • 这仅在 RT 的锚点居中时有效。这需要按照最初的要求进行调整以适当放置图像。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 2020-07-05
    • 2018-07-03
    • 1970-01-01
    • 2013-12-16
    相关资源
    最近更新 更多