【问题标题】:How to get position of click on UI element [duplicate]如何获得点击UI元素的位置[重复]
【发布时间】:2021-08-12 01:39:36
【问题描述】:

如何在 UI 对象上获得点击或触摸的点?根据我对 Raycasting 的正常方式的了解,可以查看 UI 元素无法在哪些地方完成点击。而且 OnClick 事件并没有真正提供任何额外的信息。

【问题讨论】:

  • Raycasting to see where a click lands can't be done with UI elements .. 是的,它可以:GraphicRaycaster.Raycast
  • 我也关闭了这个作为副本。如果这实际上是一个不同的问题,请随时解释原因,我们可以重新打开这个问题.. 虽然这个问题更加通用和不清楚

标签: unity3d user-interface


【解决方案1】:

我会使用IPointer 事件。

using UnityEngine.EventSystem;

public class AScriptOnYourUIElement : MonoBehaviour, IPointerClickHandler
{
    //Detect if a click occurs - this is a callback, you do NOT have to call this
    public void OnPointerClick(PointerEventData pointerEventData)
    {
        Debug.Log(pointerEventData.pointerCurrentRaycast.worldPosition);
    }
}

PointerEventData 可以为您提供很多其他数据,以及RaycastResult 提供的其他数据。

如果您不想要点击的worldPositionScreenPosition,您可以使用RectTransformUtility.ScreenPointToLocalPointInRectangle 将这些坐标转换为对象的本地RectTransform 位置。

如果您在Screen Space - Overlay 中使用Canvas,则必须将null 作为Camera 的参数传递给RectTransformUtility

文档中要提到的另一个注意事项是

在事件中使用 ScreenPointToLocalPointInRectangle 时 提供 PointerEventData 对象的处理程序,正确的相机 可以通过使用 PointerEventData.enterEventData 获得(用于悬停 功能)或 PointerEventData.pressEventCamera(点击 功能)。这将自动使用正确的相机(或 null) 对于给定的事件。

让我知道这对你有什么好处。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-13
    • 2015-06-16
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 1970-01-01
    • 2022-01-21
    相关资源
    最近更新 更多