2017年3月24日修改

vive的sdk SteamVR在升级,会有些改动。最新的SteamVR1.2.1在Unity5.4.4下狂报错。

下面的内容是在以下环境完成的

unity5.4.4




啊,为什么开始做vive的开发了,这个问题别问哦。好了,说正事。


认识下vive的手柄

请看下图

Unity开发HTC vive 一、手柄按钮_.net

Unity开发HTC vive 一、手柄按钮_vive_02

手柄两个一对,分左右,开发的时候也是分左右的。每个上面有一个pad和4个按钮。简单说明下:

  • 开关、系统菜单按钮:只有这个按钮不可以编程(默认),用来打开手柄,其实没用关的功能。在游戏中按下该按钮是调出系统默认的菜单,用来关闭,切换游戏用的。
  • menu按钮:默认用来打开游戏菜单。
  • grip按钮:用的最少的按钮,每个手柄上虽然有两个,但是是相同的。
  • trigger按钮:扳机按钮,用的最多,可以有力度。
  • pad:触摸屏+鼠标的功能,可触摸,可点击。

SDK下载

需要两个插件:

SteamVR Plugin

Unity开发HTC vive 一、手柄按钮_System_03

和Vive Input Utility

Unity开发HTC vive 一、手柄按钮_.net_04

商城地址如下,都是免费的,下载后导入

​https://www.assetstore.unity3d.com/cn/#!/content/32647​

​https://www.assetstore.unity3d.com/cn/#!/content/64219​


程序开发之综述


首先,引用HTC.UnityPlugin.Vive


using HTC.UnityPlugin.Vive;




每个按钮包括pad都有GetPress、GetPressDown、GetPressUp三种方法,用HandRole枚举来确定左右手柄,用ControllerButton枚举来确定是哪个按钮。

对于按钮,GetPressDown是按下时触发,GetPressUp是放开时触发,以上两个是个事件,GetPress是按住时一直返回ture,算是一个状态。

对于pad,有两种:

当ControllerButton.Pad时,和按钮相同。

当ControllerButton.PadTouch时,GetPressDown是接触时触发,GetPressUp是离开时触发,GetPress是接触时一直返回的状态。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using HTC.UnityPlugin.Vive;

public class viveLearn : MonoBehaviour {

// Update is called once per frame
void Update () {
if (ViveInput.GetPress (HandRole.RightHand, ControllerButton.Menu)) {
Debug.Log ("menu press");
}

if (ViveInput.GetPressUp (HandRole.RightHand, ControllerButton.Menu)) {
Debug.Log ("menu press up");
}

if (ViveInput.GetPressDown (HandRole.RightHand, ControllerButton.Menu)) {
Debug.Log ("menu press down");
}
}
}


Unity开发HTC vive 一、手柄按钮_3d_05



除了上面的方法,还可以通过回掉的方式实现

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using HTC.UnityPlugin.Vive;

public class viveLearn : MonoBehaviour {

private void Awake(){
ViveInput.AddPress (HandRole.LeftHand, ControllerButton.Menu, OnMenuPress);
}

private void OnDestory(){
ViveInput.RemovePress (HandRole.LeftHand, ControllerButton.Menu, OnMenuPress);
}

private void OnMenuPress(){
Debug.Log ("menu press");
}
}


Trigger按钮开发

Trigger有模拟值,从0到1,没按的时候是0,全部按下是1。可以通过GetTriggerValue方法获得。

ViveInput.GetTriggerValue (HandRole.LeftHand, false);


Trigger按钮,对应有三种,Trigger,HairTrigger,FullTrigger。

当TriggerValue在0.1到0.2时,对应HairTrigger,当TriggerValue超过0.5时对应Trigger,当TriggerValue=1时,对应FullTrigger。

可以简单理解为,轻按=HairTriiger,中度按=Trigger,全部按下=FullTrigger。

Unity开发HTC vive 一、手柄按钮_unity_06


Pad开发

pad做那么大,当然除了可以按,还可以返回位置信息。用GetPadAxis方法即可。

ViveInput.GetPadAxis (HandRole.LeftHand, false);

触碰位置信息如下图

Unity开发HTC vive 一、手柄按钮_vive_07



此外,对应pad,又有接触、按下的两组方法。其中,Axis是坐标位置,Delta是最后一帧移动位置,Vector是移动的向量。

ViveInput.GetPadTouchAxis (HandRole.LeftHand, false);
ViveInput.GetPadTouchDelta (HandRole.LeftHand, false);
ViveInput.GetPadTouchVector (HandRole.LeftHand, false);

ViveInput.GetPadPressAxis (HandRole.LeftHand, false);
ViveInput.GetPadPressDelta (HandRole.LeftHand, false);
ViveInput.GetPadPressVector (HandRole.LeftHand, false);