Unity XR Interaction Toolkit でコントローラーの位置を取得する方法

Unity XR インタラクション ツールキットには、コントローラーの位置を取得するさまざまな方法があります。コントローラー上に XR ダイレクト インタラクターがある場合 (他のインタラクターも機能すると考えるのは合理的です)、次のスクリプトは、コントローラーの位置と回転を取得できます。コントローラ:

using UnityEngine;
using UnityEngine.XR.Interaction.Toolkit;


public class ControllerLocation : MonoBehaviour
{
    XRDirectInteractor controller;

    Vector3 position;
    Quaternion rotation;

    void Start()
    {
        controller = GetComponent<XRDirectInteractor>();     
    }

    // Update is called once per frame
    void Update()
    {
        position = controller.transform.position;
        rotation = controller.transform.rotation;

        Debug.Log(position);
        Debug.Log(rotation);  
    }

}

実際、Unity の設計には感謝しなければなりませんが、スクリプトはコンポーネントであり、同じゲームオブジェクトに関連付けられた異なるコンポーネントは相互にアクセスできます。

CommonUsages の活用

XRコントローラーしかない場合はどうなりますか?特別なインタラクターをアタッチする必要はありません。これも非常に簡単です。実際、XRController または公式ドキュメントUnity XR Inputを開く と、答えがあります。たとえば、適切なコントローラーの場所を知りたい場合, 次に、最初に適切なコントローラーを取得しようとしてから、TryGetFeatureValue を使用して、一般的に使用される位置と回転を取得します。さらに、この CommonUsages では、ボタンが押されているかどうかなど、他の情報も取得できます。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR;


public class HandPresence : MonoBehaviour
{

    private InputDevice targetDevice;

    private Vector3 position;
    private Quaternion rotation;


    // Start is called before the first frame update
    void Start()
    {

        List<InputDevice> devices = new List<InputDevice>();
        InputDeviceCharacteristics rightControllerCharacteristics = InputDeviceCharacteristics.Right | InputDeviceCharacteristics.Controller;
        InputDevices.GetDevicesWithCharacteristics(rightControllerCharacteristics, devices);

        foreach (var item in devices)
        {
            Debug.Log( item.name + item.characteristics );
        }

        if (devices.Count > 0)
        {
            targetDevice = devices[0];
        }
    }


    // Update is called once per frame
    void Update()
    {

        targetDevice.TryGetFeatureValue(CommonUsages.devicePosition, out position);
        targetDevice.TryGetFeatureValue(CommonUsages.deviceRotation, out rotation);

        Debug.Log(position);
        Debug.Log(rotation);  
    }


}

おすすめ

転載: blog.csdn.net/qq_21743659/article/details/133167457