Version: 2019.1
空间映射常见问题故障排除
Windows Mixed Reality 的输入

Unity XR 输入

This section provides information on all Unity-supported input devices for virtual reality, augmented reality and Windows Mixed Reality applications. This page is broken up into the following sections:

XR platforms typically provide a rich diversity of input features for you to take advantage of when designing user interactions. Positions, rotations, touch, buttons, joysticks, and finger sensors all provide specific pieces of data.

At the same time, access to these input features vary between different XR platforms. The Vive and the Oculus Rift have subtle differences, while there are drastic differences between a desktop VR platform and a mobile platform like Daydream.

Unity provides a C# struct called InputFeatureUsage, which defines a standard set of physical device elements (such as buttons and triggers) to access user input in a platform-agnostic way. These help you quickly identify input types by name. See XR.Input.CommonUsages for a definition of each InputFeatureUsage.

Each InputFeatureUsage corresponds to a common input action or type. For example, Unity defines the InputFeatureUsage called trigger as a single-axis input controlled by the index finger, regardless of which XR platform you use. You can use InputFeatureUsage to get the trigger state by name, so you don’t need to set up an axis (or a button on some XR platforms) for the conventional Unity Input system.

XR 输入映射

下表列出了标准控制器 InputFeatureUsage 的名称以及它们与常见 XR 系统的控制器之间的映射关系:

InputFeatureUsage FeatureType Legacy Input Index [L/R] WMR Oculus GearVR Daydream OpenVR (Full) Vive OpenVR
(
Oculus)
OpenVR (WMR)
primary2DAxis 2D 轴 [(1,2)/(4,5)] 游戏杆 游戏杆 游戏杆 触控板 [触控板/游戏杆] 触控板 游戏杆 游戏杆
trigger [9/10] 触发器 触发器 触发器 触发器 触发器 触发器 触发器 触发器
grip [11/12] 握把 握把 握把 握把 握把 握把 握把
indexTouch [13/14] 食指 - 近触控
thumbTouch [15/16] 拇指 - 近触控
secondary2DAxis 2D 轴 [(17,18)/(19,20)] 触控板 触控板
indexFinger [21/22] 食指
middleFinger [23/24] 中指
ringFinger [25/26] 无名指
pinkyFinger [27/28] 小指
combinedTrigger [3/3] 组合触发器 组合触发器 组合触发器 组合触发器 组合触发器 组合触发器
primaryButton 按钮 [2/0] [X/A] 应用程序 主要 主要 主要 [Y/B] 菜单
primaryTouch 按钮 [12/10] [X/A] - 触控
secondaryButton 按钮 [3/1] [Y/B] 备用 备用 [B/A]
secondaryTouch 按钮 [13/11] [Y/B] - 触控
gripButton 按钮 [4/5] 握把 - 按下 握把 - 按下 握把 - 按下 握把 - 按下 握把 - 按下 握把 - 按下 握把
triggerButton 按钮 [14/15] 触发器 - 按下 食指 - 触控 触发器 - 按下 触发器 - 按下 触发器 - 按下 触发器 - 按下 触发器 - 触控 触发器 - 按下
menuButton 按钮 [6/7] 菜单 开始 (6)
primary2DAxisClick 按钮 [8/9] 触控板 - 单击 控制杆 - 单击 触控板 - 单击 触控板 - 单击 StickOrPad - 按下 StickOrPad - 按下 StickOrPad - 按下 触控板 - 单击
primary2DAxisTouch 按钮 [16/17] 触控板 - 触摸 控制杆 - 触控 触控板 - 触摸 触控板 - 触摸 StickOrPad - 触控 StickOrPad - 触控 StickOrPad - 触控 触控板 - 触摸
thumbrest 按钮 [18/19] 游戏杆 - 单击 ThumbRest - 触控

有关每个 InputFeatureUsage 的定义,请参阅 XR.Input.CommonUsages

访问输入设备

An InputDevice represents any physical device, such as a controller, cellular phone, or headset, and can contain information on device tracking, buttons, joysticks, and other input controls. See InputDevice for more information on the InputDevice API.

Use the XR.InputDevices class to access input devices (such as controllers and trackers) that are currently connected to the XR system. Use InputDevices.GetDevices to get a list of all connected devices:

var inputDevices = new List<UnityEngine.XR.InputDevice>();
UnityEngine.XR.InputDevices.GetDevices(inputDevices);

foreach (var device in inputDevices)
{
    Debug.Log(string.Format("Device found with name '{0}' and role '{1}'", device.name, device.role.ToString()));
}

An InputDevice remains valid across frames until the XR system disconnects it. Use the InputDevice.IsValid property to determine whether an InputDevice still represents an active controller.

按角色访问输入设备

设备角色描述输入设备的一般功能。请使用 InputDeviceRole 枚举来指定设备角色。定义的角色有:

  • GameController: a console-style game controller.
  • Generic: A device that represents the core XR device, such as a head-mounted display or mobile device.
  • HardwareTracker: a tracking device.
  • LeftHanded: a device associated with the user’s left hand.
  • RightHanded: a device associated with the user’s right hand.
  • TrackingReference: a device that tracks other devices, such as an Oculus tracking camera.

The underlying XR SDK reports these roles, and different providers can organize their device roles differently. Additionally, a user can switch hands, so the role assignment might not match the hand the user is using to hold the input device. For example, a user must set up the Daydream controller as right or left-handed, but can choose to hold the controller in the opposite hand.

GetDevicesWithRole 提供具有特定 InputDeviceRole 的所有设备的列表。例如,您可以使用 InputDeviceRole.GameController 获取任何已连接的 GameController 设备:

var gameControllers = new List<UnityEngine.XR.InputDevice>();
UnityEngine.XR.InputDevices.GetDevicesWithRole(UnityEngine.XR.InputDeviceRole.GameController, gameControllers);

foreach (var device in gameControllers)
{
    Debug.Log(string.Format("Device name '{0}' has role '{1}'", device.name, device.role.ToString()));
}

按 XR 节点访问输入设备

XR nodes represent the physical points of reference in the XR system. The user’s head position, their right and left hands, and a tracking reference such as an Oculus camera are all XR nodes. The XRNode enumeration defines the available nodes. The defined nodes are:

  • CenterEye: a point midway between the pupils of the user’s eyes.

  • GameController: a console-style game controller. Multiple game controller nodes can exist.

  • HardwareTracker: a hardware tracking device, typically attached to the user or a physical item. Multiple hardware tracker nodes can exist.

  • Head: the center point of the user’s head, as calculated by the XR system.

  • LeftEye: the user’s left eye.

  • LeftHand: the user’s left hand.

  • RightEye: the user’s right eye.

  • RightHand: the user’s right hand.

  • TrackingReference: a tracking reference point, such as the Oculus camera. Multiple tracking reference nodes can exist.

请使用 InputDevices.GetDevicesAtXRNode 来获取与特定 XRNode 关联的设备列表。下面的示例演示了如何获取惯用左手的控制器:

var leftHandDevices = new List<UnityEngine.XR.InputDevice>();
UnityEngine.XR.InputDevices.GetDevicesAtXRNode(UnityEngine.XR.XRNode.LeftHand, leftHandDevices);

if(leftHandDevices.Count == 1)
{
    UnityEngine.XR.InputDevice device = leftHandDevices[0];
    Debug.Log(string.Format("Device name '{0}' with role '{1}'", device.name, device.role.ToString()));
}
else if(leftHandDevices.Count > 1)
{
    Debug.Log("Found more than one left hand!");
}

访问输入设备上的输入功能

You can read an input feature, such as the state of a trigger button, from a specific InputDevice. To read the state of the right trigger, first get an instance of the right-handed device using InputDeviceRole.RightHanded or XRNode.RightHand. Once you have the correct device, use the InputDevice.TryGetFeatureValue function to access the current state.

TryGetFeatureValue() attempts to access the current value of a feature, but can fail if the current device does not support the specified feature or the device is invalid (a controller is no longer active). The function returns true if it successfully retrieves the specified feature value, and returns false if it fails.

To get a particular button, touch input, or joystick axis value, use the CommonUsages class. CommonUsages includes each InputFeatureUsage in the XR input mapping table, as well as tracking features like position and rotation. The following code example uses CommonUsages.triggerButton to detect whether the player is currently pulling the trigger button on a particular InputDevice instance:

bool triggerValue;
if (device.TryGetFeatureValue(UnityEngine.XR.CommonUsages.triggerButton, out triggerValue) && triggerValue)
{
    Debug.Log("Trigger button is pressed");
}

You can also use the InputDevice.TryGetFeatureUsages function to get a list of every InputFeatureUsage that a device provides. This function returns a list of InputFeatureUsage items, which have a type and name property describing the feature. The following example enumerates all of the Boolean features provided by a given input device:

var inputFeatures = new List<UnityEngine.XR.InputFeatureUsage>();
if (device.TryGetFeatureUsages(inputFeatures))
{
    foreach (var feature in inputFeatures)
    {
        if (feature.type == typeof(bool))
        {
            bool featureValue;
            if (device.TryGetFeatureValue(feature.As<bool>(), out featureValue))
            {
                Debug.Log(string.Format("Bool feature '{0}''s value is '{1}'", feature.name, featureValue.ToString()));
            }
        }
    }
}

primaryButton 的示例

Different controller configurations can provide access to different features; such as multiple controllers on one system, different controllers on different systems, or different buttons on the same controllers with different SDKs. This diversity makes it more complicated to support input from a range of XR systems. The Unity InputFeatureUsage API helps you get input in an XR platform-agnostic way.

The following example accesses the InputFeatureUsage called primaryButton, no matter which controller or input device provides it. The example includes a class that scans the available devices for the primaryButton. The class monitors the value of the feature on any connected device and if the value changes, the class dispatches a UnityEvent.

To use this class, add it as a component to any GameObject in the Scene.

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

[System.Serializable]
public class PrimaryButtonEvent : UnityEvent<bool>{}

public class PrimaryButtonWatcher : MonoBehaviour
{
    public PrimaryButtonEvent primaryButtonPress;
    
    private bool lastButtonState = false;
    private List<UnityEngine.XR.InputDevice> allDevices;
    private List<UnityEngine.XR.InputDevice> devicesWithPrimaryButton;
    
    void Start()
    {
        if(primaryButtonPress == null)
        {
            primaryButtonPress = new PrimaryButtonEvent();
        }
        allDevices = new List<UnityEngine.XR.InputDevice>();
        devicesWithPrimaryButton = new List<UnityEngine.XR.InputDevice>();
        InputTracking.nodeAdded += InputTracking_nodeAdded;
    }

    // check for new input devices when new XRNode is added
    private void InputTracking_nodeAdded(XRNodeState obj)
    {
        updateInputDevices();
    }

    void Update()
    {
        bool tempState = false;
        bool invalidDeviceFound = false;
        foreach(var device in devicesWithPrimaryButton)
        {
            bool primaryButtonState = false;
            tempState = device.isValid // the device is still valid
                        && device.TryGetFeatureValue(CommonUsages.primaryButton, out primaryButtonState) // did get a value
                        && primaryButtonState // the value we got
                        || tempState; // cumulative result from other controllers
            if (!device.isValid)
                invalidDeviceFound = true;
        }

        if (tempState != lastButtonState) // Button state changed since last frame
        {
            primaryButtonPress.Invoke(tempState);
            lastButtonState = tempState;
        }

        if (invalidDeviceFound || devicesWithPrimaryButton.Count == 0) // refresh device lists
            updateInputDevices();
    }

    // find any devices supporting the desired feature usage
    void updateInputDevices()
    {
        devicesWithPrimaryButton.Clear();
        UnityEngine.XR.InputDevices.GetDevices(allDevices);
        bool discardedValue;
        foreach (var device in allDevices)
        {
            if(device.TryGetFeatureValue(CommonUsages.primaryButton, out discardedValue))
            {
                devicesWithPrimaryButton.Add(device); // Add any devices that have a primary button.
            }
        }
    }
}

The following PrimaryReactor class uses the PrimaryButtonWatcher to detect when you press a primary button and, in response to a press, rotates its parent GameObject. To use this class, add it to a visible GameObject, such as a Cube, and drag the PrimaryButtonWatcher reference to the watcher property.

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

public class PrimaryReactor : MonoBehaviour
{
    public PrimaryButtonWatcher watcher;
    public bool IsPressed = false; // used to display button state in the Unity Inspector window
    public Vector3 rotationAngle = new Vector3(45, 45, 45);
    public float rotationDuration = 0.25f; // seconds
    private Quaternion offRotation;
    private Quaternion onRotation;
    private Coroutine rotator;

    void Start()
    {
        watcher.primaryButtonPress.AddListener(onPrimaryButtonEvent);
        offRotation = this.transform.rotation;
        onRotation = Quaternion.Euler(rotationAngle) * offRotation;
    }

    public void onPrimaryButtonEvent(bool pressed)
    {
        IsPressed = pressed;
        if (rotator != null)
            StopCoroutine(rotator);
        if (pressed)
            rotator = StartCoroutine(AnimateRotation(this.transform.rotation, onRotation));
        else
            rotator = StartCoroutine(AnimateRotation(this.transform.rotation, offRotation));
    }

    private IEnumerator AnimateRotation(Quaternion fromRotation, Quaternion toRotation)
    {
        float t = 0;
        while(t < rotationDuration)
        {
            transform.rotation = Quaternion.Lerp(fromRotation, toRotation, t/rotationDuration);
            t += Time.deltaTime;
            yield return null;
        }
    }
}

通过旧版输入系统实现 XR 输入

You can poll XR input features via the legacy input system by using the appropriate legacy input indices from the XR input mappings table. Create an axis mapping in Edit > Settings > Input to add the appropriate mapping from input name to axis index for the platform device’s feature. To retrieve the button or axis value, use Input.GetAxis or Input.GetButton and pass in the now-mapped axis or button name.

For more information about how to use the button and joystick axes, see the documentation on Conventional game input.

触觉

You can send haptic events to an InputDevice. Unity supports haptics as either a simple impulse with amplitude and duration, or as a buffer of data.

并非所有平台都支持所有类型的触觉,但您可以查询设备的触觉功能。以下示例获取右手的输入设备,检查设备是否具有触觉功能,然后在有触觉功能的情况下再现脉冲:

List<UnityEngine.XR.InputDevice> devices = new List<UnityEngine.XR.InputDevice>(); 

UnityEngine.XR.InputDevices.GetDevicesWithRole(UnityEngine.XR.InputDeviceRole.RightHanded, devices);

foreach (var device in devices)
{
    UnityEngine.XR.HapticCapabilities capabilities;
    if (device.TryGetHapticCapabilities(out capabilities))
    {
            if (capabilities.supportsImpulse)
            {
                uint channel = 0;
                float amplitude = 0.5f;
                float duration = 1.0f;
                device.SendHapticImpulse(channel, amplitude, duration);
            }
    }
}

  • New functionality and behaviour in 2019.1 NewIn20191
空间映射常见问题故障排除
Windows Mixed Reality 的输入
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961