使用SteamVR实现与物体的交互

8 篇文章 2 订阅
6 篇文章 0 订阅
使用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<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);
        }
    }
}
  • 1
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值