本节目标
1、如何获得按钮事件?
2、如何获得事件传递的数据?
3、抓取的基本原理?
4、手柄震动的实现?
案例流程
手柄碰触盒子时,扣动扳机键,拿起盒子。松开扳机键,放下盒子
实现步骤
1、导入SteamVR SDK、Standard Assets
2、拖入[CameraRig],放入地面、盒子
3、获取手柄引用
private SteamVR_TrackedObject trackedObject;
private SteamVR_Controller.Device device;
// Use this for initialization
void Start () {
trackedObject = GetComponent<SteamVR_TrackedObject>();
device = SteamVR_Controller.Input((int)trackedObject.index);
}
4、手柄与Box的碰撞检测
给两个Controller添加Sphere Collider,勾选Is Trigger,给盒子添加Rigidbody
private void OnTriggerEnter(Collider other){ }
private void OnTriggerExit(Collider other){ }
5、获取按钮事件
void Update () {
if (device.GetPressDown(SteamVR_Controller.ButtonMask.Trigger)){ }
if (device.GetPressUp(SteamVR_Controller.ButtonMask.Trigger)){ }
}
6、手柄震动
device.TriggerHapticPulse(700);
7、抓取和松开事件的实现
改变cube的父物体对象,改变cube是否使用重力和动力学Is Kinematic
Is Kinematic:是否开启动力学,开启则游戏不再受物理引擎影响,只受transform影响
全代码展示:
using UnityEngine;
public class MyController : MonoBehaviour {
private SteamVR_TrackedObject trackedObject;
private SteamVR_Controller.Device device;
private GameObject interactBox;
void Start () {
trackedObject = GetComponent<SteamVR_TrackedObject>();
device = SteamVR_Controller.Input((int)trackedObject.index);
}
void Update () {
if (device.GetPressDown(SteamVR_Controller.ButtonMask.Trigger))
{
if (interactBox != null)
{
interactBox.transform.parent = transform;
interactBox.GetComponent<Rigidbody>().useGravity = false;
interactBox.GetComponent<Rigidbody>().isKinematic = true;
}
}
if (device.GetPressUp(SteamVR_Controller.ButtonMask.Trigger))
{
if (interactBox != null)
{
interactBox = null;
interactBox.transform.parent = transform.parent.parent;
interactBox.GetComponent<Rigidbody>().useGravity = true;
interactBox.GetComponent<Rigidbody>().isKinematic = false;
}
}
}
private void OnTriggerEnter(Collider other)
{
interactBox=other.transform.gameObject;
}
private void OnTriggerExit(Collider other)
{
interactBox = null;
}
private void OnTriggerStay(Collider other)
{
if (device != null)
{
device.TriggerHapticPulse(700);
}
}
}