【问题标题】:Unity raycasts going through UI通过 UI 的 Unity 光线投射
【发布时间】:2018-08-28 19:12:09
【问题描述】:

我试图阻止光线投射通过我的按钮 2d UI。目前,当按钮后面没有游戏对象时,按钮可以正常工作,但是当后面有游戏对象时,它会触发对象而不是我的按钮。我曾尝试使用以下代码尝试检测 UI,但它似乎不起作用,并且不断返回 True:

EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId));

任何帮助将不胜感激。

编辑:

我当前的代码:

 void Update () {
    if (!EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId)){
        RegisterModelTouch();
    }

}

public void RegisterModelTouch() {
    // We assume that there was only one touch and take the first 
    // element in the array.

    try {
        Touch touch = Input.touches[0];
        RaycastHit hit;
        Ray ray = Camera.main.ScreenPointToRay(touch.position);


        if (Physics.Raycast(ray, out hit)) {
           if (hit.collider.CompareTag("Mytag")) {
              //Do model stuff here
            }

        }
    }
    catch (Exception e) {
        return;
    }
}

【问题讨论】:

  • IsPointerOverGameObject 是执行此操作的正确方法。您必须发布比赛代码(raycast + IsPointerOverGameObject 代码)。顺便说一句,在您的情况下,光线投射到底是做什么用的?
  • 我正在开发一个增强现实应用程序。光线投射是为了让用户可以点击 3d 模型的各个部分,并弹出有关该部分的信息。我有一个默认的 Physics Raycast 组件连接到我的相机。为了简单起见,我一直在Update() 中打印isPointerOverGameObject 的值,它不断返回True。
  • 您需要添加代码。请注意,Input.GetTouch 只能在移动设备上运行,因此请确保您正在对此进行测试
  • 是的,我现在正在 iPad Pro 上进行测试。我需要什么代码?很抱歉,我对 Unity 很陌生。
  • 你说你的 raycast 是通过 ui 的?您必须编辑您的问题并添加您的光线投射代码 + 您如何使用 EventSystem.current.IsPointerOverGameObject 来防止这种情况。您的问题中没有代码,如果没有代码,任何人都很难为您提供帮助

标签: c# unity3d vuforia raycasting


【解决方案1】:

我的解决方案深埋在论坛讨论中:

/// <summary>
/// Cast a ray to test if Input.mousePosition is over any UI object in EventSystem.current. This is a replacement
/// for IsPointerOverGameObject() which does not work on Android in 4.6.0f3
/// </summary>
private bool IsPointerOverUIObject() {
    // Referencing this code for GraphicRaycaster https://gist.github.com/stramit/ead7ca1f432f3c0f181f
    // the ray cast appears to require only eventData.position.
    PointerEventData eventDataCurrentPosition = new PointerEventData(EventSystem.current);
    eventDataCurrentPosition.position = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
 
    List<RaycastResult> results = new List<RaycastResult>();
    EventSystem.current.RaycastAll(eventDataCurrentPosition, results);
    return results.Count > 0;
}

从这里:https://forum.unity.com/threads/ispointerovereventsystemobject-always-returns-false-on-mobile.265372/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多