Unity+Pico(四):手柄按键控制

一、定义手柄按键API

1、需要使用XR的命名空间(using UnityEngine.XR;)才能调用按键相关的API;

2、InputDevices.GetDeviceAtXRNode,通过XRNode获取对应的设备;

3、XRNode是一个枚举类型,包含LeftEye、RightEye、CenterEye、Head、LeftHand、RightHand、GameController、TrackingReference、HardwareTracker;

4、TryGetFeatureValue,得到某个特性的值;

5、CommonUsages定义了用于从XR.InputDevice.TryGetFeatureValue获取输入特征的静态变量,用来指定想要获取的特性。

以下例子为获取左手柄的摇杆数据,以及右手柄是否按下抓取键、是否按下扳机键、是否按下菜单键、是否按下主键、是否按下副键的代码。

Vector2 vec2DAxis = Vector2.zero;
bool isGrip = false;
bool isTrigger = false;
bool isMenu = false;
bool isPrimaryButton = false;
bool isSecondButton = false;
InputDevices.GetDeviceAtXRNode(XRNode.LeftHand).TryGetFeatureValue(CommonUsages.primary2DAxis, out vec2DAxis);
InputDevices.GetDeviceAtXRNode(XRNode.RightHand).TryGetFeatureValue(CommonUsages.gripButton, out isGrip);
InputDevices.GetDeviceAtXRNode(XRNode.RightHand).TryGetFeatureValue(CommonUsages.triggerButton, out isTrigger);
InputDevices.GetDeviceAtXRNode(XRNode.RightHand).TryGetFeatureValue(CommonUsages.menuButton, out isMenu);
InputDevices.GetDeviceAtXRNode(XRNode.RightHand).TryGetFeatureValue(CommonUsages.primaryButton, out isPrimaryButton);
InputDevices.GetDeviceAtXRNode(XRNode.RightHand).TryGetFeatureValue(CommonUsages.secondaryButton, out isSecondButton);

二、控制物体移动

编写脚本用手柄控制物体的前后左右移动,如果把脚本挂载到头显上,就变成控制自身的移动。 

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

public class ControlObject : MonoBehaviour
{
    // Update is called once per frame
    void Update()
    {
        Vector2 vec2DAxis = Vector2.zero;
        InputDevices.GetDeviceAtXRNode(XRNode.LeftHand).TryGetFeatureValue(CommonUsages.primary2DAxis, out vec2DAxis);
        transform.position = new Vector3(transform.position.x + vec2DAxis.x * Time.deltaTime,
            transform.position.y, transform.position.z + vec2DAxis.y * Time.deltaTime);
    }
}

 

posted @ 2023-01-10 14:50  zero_to_infinity  阅读(6360)  评论(0编辑  收藏  举报