【问题标题】:How do I convert point to local coordinates?如何将点转换为局部坐标?
【发布时间】:2015-08-25 02:03:07
【问题描述】:

当用户点击按钮时,如果点击了透明像素,我希望忽略点击,而它下方的按钮应该接收点击。

我可以在几分钟内在目标 c 中执行这种行为,但是,尝试在 C# 中的 Unity 中执行此操作已被证明是不可能的,因为无法将屏幕上的点转换为本地点。显然中心或左下角,或者左上角应该是原点(我不知道是哪个,因为Unity会根据月相不断改变原点的位置)

我已尝试查看 ICanvasRaycastFilter 中的 IsRaycastLocationValid 在里面我使用了 RectTransformUtility.ScreenPointToLocalPointInRectangle 和 RectTransformUtility.ScreenPointToWorldPointInRectangle ,结果总是一样的。我给的 RectTransform 是属于按钮的那个。

例如:

public bool IsRaycastLocationValid(Vector2 screenPosition, Camera raycastEventCamera) //uGUI callback
    {

        Vector2 localPoint;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, screenPosition, null, out localPoint);

        Vector2 pivot = rectTransform.pivot - new Vector2(0.5f, 0.5f);

        Vector2 pivotScaled = Vector2.Scale(rectTransform.rect.size, pivot);

        Vector2 realPoint = localPoint + pivotScaled;

        Debug.Log(screenPosition + " " + localPoint);

        return false;
    }

这是我从其他人的未答复尝试中得到的 Unity 3d 4.6 Raycast ignore alpha on sprite

我找到了这个链接 http://forum.unity3d.com/threads/alpha-area-on-round-gui-button-return-click-event.13608/ 有人试图确定 mousePosition 是否在图像范围内。明显的问题是图像必须在 (100,100) 处有某个角。幻数很糟糕,试图弄清楚如何获得这些坐标几乎是不可能的。

无论您将按钮放在何处,RectTransform 上的以下属性始终相同:

anchoredPosition    
anchoredPosition3D  
anchorMax   
anchorMin   
offsetMax   
offsetMin   
pivot   
rect    
sizeDelta

如您所见,这就是 RectTransform 具有的所有属性。因此无法判断按钮在哪里,也无法判断点击在按钮的坐标空间中的位置。

有人可以告诉我该怎么做吗?

【问题讨论】:

  • 请使用 unity3d 标签。

标签: c# user-interface button unity3d


【解决方案1】:

应该做的伎俩:

bool isScreenPointInsideRectTransform( Vector2 screenPoint, RectTransform transform, Camera canvasCamera )
{
    Vector2 localPoint;
    RectTranformUtility.ScreenPointToLocalPointInRectangle( transform, screenPoint, canvasCamera, out localPoint );
    return transform.rect.Contains( localPoint );
}

【讨论】:

  • ScreenPointToLocalPointInRectangle 如果碰到 RectTransform 的平面,则返回 true,无论该点是否在矩形内。
【解决方案2】:

这正是为什么您没有找到按钮本身内部点的位置的原因......但是您比较该点在 parent 矩形内的位置按钮和按钮 localPosition 本身。

或者您可以将像素点转换为屏幕位置,然后与鼠标位置进行比较

【讨论】:

  • 抱歉打扰了,我不确定我是否完全理解。我怎样才能知道点在父矩形内的位置?如果我在计算中使用父矩形变换,它仍然是错误的。原点不在按钮应位于原点的位置附近。
  • 您使用RectTransformUtility.ScreenPointToLocalPointInRectangle() 得到的点是仅在您给它的矩形中的一个点,那么您是在比较同一地点的点吗?另外,您是否会遇到相反的情况并一起比较屏幕点?
  • 嗯...我不敢相信...原来我一直在通过错误的矩形...
  • 嗨。那么什么是解决方案?我想查看正确示例的整个脚本。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-29
  • 1970-01-01
相关资源
最近更新 更多