Unity MRTK with HoloLens 2:如何在代码中检测手是否触摸到游戏对象?

Unity MRTK with HoloLens 2: How to detect whether a hand touches a GameObject in code?

我一直在使用 Unity 2020.3 LTS、Windows XR 插件和令人惊叹的 MRTK 2.7.0 将现有应用程序移植到 HoloLens 2。

在这个应用程序中,我有一个包含多个游戏对象的场景,我需要检测手是否触摸了游戏对象(使用食指尖近交互或捏合手势远交互)。这里的重要部分是这种检测需要在场景的中央脚本中发生(即可能将手作为代码中的对象)而不是从被触摸的游戏对象本身的角度来看。

我已经使用 this example 和该页面下方的两个代码示例成功实现了后者,但是被触摸的 GameObject 本身通过侦听器触发事件​​不适用于我的用例。可以说,我需要从手的角度检测触摸。

为此,我多次在网络和 Microsoft MRTK 文档中进行搜索,不幸的是,我找不到任何有帮助的信息。对于头部注视,文档有一个超级简单的代码示例,效果很好:Head-gaze in Unity。我需要完全相同的东西来检测手何时触摸游戏对象。

最终,我在查看游戏对象时也需要同样的眼动追踪功能,但我还没有研究过这个,现在手部交互让我很头疼。我希望有人可以帮助我。提前致谢:).

but the touched GameObject itself firing events via a listener does not work well with my use case.

为什么活动不成功?你能提供更多细节吗?

除了NearInteractionTouchable,你有没有试过Interactable component? It's usually used to attach to the touched Game Object and will fire the event receiver when catching input actions. In the event receiver (in the Component UI), you can add any function attached to any object as the listener, such as a central script in the scene. It should be an effortless way can meet your request. For more information please see: Event

经过一些额外的摆弄之后,我能够让它像我 want/need 与 Touch Code Example 一样工作。解决方案是在中央脚本的代码中创建一个空的 GameObject 变量,不断检查它是否为 null。只要触摸了 GameObject 本身,它就会将自身绑定到选中的 GameObject 变量,并在不再触摸后将其设置回 null。这允许中央脚本在被触摸的 GameObject 上工作,只要它被触摸。

    void Start()
    {
        centralScript = GameObject.Find("Scripts").GetComponent<CentralScript>();

        NearInteractionTouchableVolume touchable = gameObject.AddComponent<NearInteractionTouchableVolume>();
        touchable.EventsToReceive = TouchableEventType.Pointer;
        pointerHandler = gameObject.AddComponent<PointerHandler>();

        pointerHandler.OnPointerDown.AddListener((e) =>
        {
        centralScript.handTouchGameObject = gameObject;
        });

    pointerHandler.OnPointerUp.AddListener((e) =>
        {
        centralScript.handTouchGameObject = null;
        });
    }