利用HTC-VIVE抓取物体
要点:
1.脚本中使用SteamVR_TrackedObject类的对象获取手柄的steamVR组件
2.利用SteamVR_Controller.Device对象使用SteamVR_Controller.Input()方法将获取的手柄转换为unity内可被识别的对象
3.使用SteamVR_Controller.Device对象的GetPressDown、GetPressUp方法获取按下、弹起操作。
4.3中方法的参数为手柄具体按钮,通过SteamVR_Controller.ButtonMask获取,Trigger参数为“扳机”。
实例代码如下:
public class CatchBox : MonoBehaviour {
//获取手柄的steamVR组件
private SteamVR_TrackedObject trackObject;
//将手柄转换为unity内可被识别的装置
private SteamVR_Controller.Device device;
//手柄抓取的物体
private GameObject catchObject;
// Use this for initialization
void Start () {
trackObject = this.GetComponent<SteamVR_TrackedObject>();
device = SteamVR_Controller.Input((int)trackObject.index);
}
void Update()
{
//监听手柄按钮事件
if (device.GetPressDown(SteamVR_Controller.ButtonMask.Trigger))
{
if (catchObject != null)
{
catchObject.transform.parent = this.transform;
Rigidbody rig = catchObject.GetComponent<Rigidbody>();
rig.useGravity = false;
rig.isKinematic = true;
}
}
if (device.GetPressUp(SteamVR_Controller.ButtonMask.Trigger))
{
if (catchObject != null)
{
catchObject.transform.parent = null;
Rigidbody rig = catchObject.GetComponent<Rigidbody>();
rig.useGravity = true;
rig.isKinematic = false;
}
}
}
/// <summary>
/// 碰撞体进入处理函数
/// </summary>
/// <param name="other"></param>
private void OnTriggerEnter(Collider other)
{
if (other.transform.tag == "Finish")
{
catchObject = other.gameObject;
}
}
private void OnTriggerStay(Collider other)
{
if (device != null) {
//使手柄发生振动
device.TriggerHapticPulse(700);
}
}
/// <summary>
/// 碰撞体结束处理函数
/// </summary>
/// <param name="other"></param>
private void OnTriggerExit(Collider other)
{
catchObject = null;
}
}