使用SteamVR实现与物体的交互需要考虑如下问题:
如何获得按钮事件?如何获得按钮传递的数据?抓取的基本原理(Collider,Rigibody)以及手柄震动的实现
使用SteamVR实现与物体的交互实现步骤
- 获取手柄引用
- 手柄与Box的碰撞检测
- 获取按钮事件
- 抓取:Box作为手柄的transform的子物体,失去rigibody相关属性
- 松开:Box的parent为空,重新获取自身的rigibody相关属性
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InterationWithBox : MonoBehaviour {
private SteamVR_TrackedObject trackedObject;
private SteamVR_Controller.Device device;
private GameObject interactBox;
// Use this for initialization
void Start ()
{
trackedObject = GetComponent<SteamVR_TrackedObject>();
device = SteamVR_Controller.Input((int)trackedObject.index);
}
// Update is called once per frame
void Update ()
{
if (device==null)
{
return;
}
if (device.GetAxis().x!=0||device.GetAxis().y!=0)
{
Debug.Log(device.GetAxis().x+"|"+device.GetAxis().y);
}
if (device.GetPressDown(SteamVR_Controller.ButtonMask.Trigger))
{
if (interactBox!=null)
{
interactBox.transform.parent = transform;
Rigidbody rig = interactBox.GetComponent<Rigidbody>();
rig.useGravity = false;
rig.isKinematic = true;
}
}
if (device.GetPressUp(SteamVR_Controller.ButtonMask.Trigger))
{
interactBox.transform.parent = null;
Rigidbody rig = interactBox.GetComponent<Rigidbody>();
rig.useGravity = true;
rig.isKinematic = false;
}
}
/// <summary>
/// 碰撞体进入处理函数
/// </summary>
/// <param name="other"></param>
private void OnTriggerEnter(Collider other)
{
Debug.Log("TriggerEnter");
interactBox = other.transform.gameObject;
}
/// <summary>
/// 碰撞体脱离处理函数
/// </summary>
/// <param name="other"></param>
private void OnTriggerExit(Collider other)
{
Debug.Log("TriggerExit");
interactBox = null;
}
private void OnTriggerStay(Collider other)
{
if (device != null)
{
device.TriggerHapticPulse(800);
}
}
}