How to get controller position in Unity XR Interaction Toolkit

Unity XR Interaction Toolkit has many ways to obtain the position of the controller. If there is an XR Direct Interactor on the controller (it is reasonable to suspect that other interactors will also work), the following script can obtain the position and rotation of the controller:

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);  
    }

}

In fact, we have to thank Unity for its design. A script is a component, and different components attached to the same GameObject can access each other.

Utilizing CommonUsages

What if there is only XR controller? I don’t want to attach any special interactor. This is also very easy. In fact, if you open XRController or the official document Unity XR Input  , there are answers. For example, if I want to know the location of the right controller, then I first try to get the right controller, and then use TryGetFeatureValue to get the commonly used position and rotation. In addition, you can also get other things in this CommonUsages, such as whether the button is pressed, etc.:

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);  
    }


}

Guess you like

Origin blog.csdn.net/qq_21743659/article/details/133167457