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获取输入特征的静态变量,用来指定想要获取的特性。
以下例子为获取左手柄的摇杆数据,以及右手柄是否按下抓取键、是否按下扳机键、是否按下菜单键、是否按下主键、是否按下副键的代码。
1 2 3 4 5 6 7 8 9 10 11 12 | 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); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?