使用SteamVR实现与物体的交互

使用SteamVR实现与物体的交互需要考虑如下问题:

    如何获得按钮事件?如何获得按钮传递的数据?抓取的基本原理(Collider,Rigibody)以及手柄震动的实现

使用SteamVR实现与物体的交互实现步骤

  1. 获取手柄引用
  2. 手柄与Box的碰撞检测
  3. 获取按钮事件
  4. 抓取:Box作为手柄的transform的子物体,失去rigibody相关属性
  5. 松开: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();
        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();
                rig.useGravity = false;
                rig.isKinematic = true;
            }
        }
        if (device.GetPressUp(SteamVR_Controller.ButtonMask.Trigger))
        {
            interactBox.transform.parent = null;
            Rigidbody rig = interactBox.GetComponent();
            rig.useGravity = true;
            rig.isKinematic = false;
        }
    }
    /// 
    /// 碰撞体进入处理函数
    /// 
    /// 
    private void OnTriggerEnter(Collider other)
    {
        Debug.Log("TriggerEnter");
        interactBox = other.transform.gameObject;
    }
    /// 
    /// 碰撞体脱离处理函数
    /// 
    /// 
    private void OnTriggerExit(Collider other)
    {
        Debug.Log("TriggerExit");
        interactBox = null;
    }

    private void OnTriggerStay(Collider other)
    {
        if (device != null)
        {
            device.TriggerHapticPulse(800);
        }
    }
}

你可能感兴趣的:(AR/VR,Unity3D,HTC,Vive开发)