当前位置:网站首页>[转]SteamVR 1.x️一、实现手与物体交互——基于[CameraRig]

[转]SteamVR 1.x️一、实现手与物体交互——基于[CameraRig]

2023-01-19 15:24:15小小姑娘很大

目录

* 实现目标:

* 实现步骤


* 实现目标:

手柄碰触盒子时,扣动扳机键,拿起盒子(Cube)。松开扳机键,放下盒子

a、获取手柄引用

b、手柄与Box的碰撞检测

c、获取按钮事件

d、抓取:Box作为手柄transform的子物体,失去rigibody相关属性

e、松开:Box的parent为空,重新获取自身rigibody相关属性

* 实现步骤

1、导入SteamVR SDK

2、删掉原Camera,拖入[CameraRig]、新建盒子、地面

可调整头部大小:[CameraRig]——SteamVR_PlayArea——Size

3、获取手柄引用

该脚本挂在右手上,即Controller (right)

    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,Collider并稍微缩小到合适大小,勾选Is Trigger,给盒子添加Rigidbody

    private void OnTriggerEnter(Collider other){ }
    private void OnTriggerExit(Collider other){ }

5、获取按钮事件

	void Update () {
        if (device.GetPressDown(SteamVR_Controller.ButtonMask.Touchpad)){ }
        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 {
    SteamVR_TrackedObject trackedObject;
    SteamVR_Controller.Device device;
    //获取到的碰撞到的box
    GameObject interactBox;
    // Use this for initialization
    void Start()
    {
        trackedObject = GetComponent<SteamVR_TrackedObject>();
        device = SteamVR_Controller.Input((int)trackedObject.index);
    }
    void Update()
    {
        //按下Trigger键
        if (device.GetPressDown(SteamVR_Controller.ButtonMask.Trigger))
        {
            if (interactBox != null)
            {
                interactBox.transform.parent = transform;
                interactBox.GetComponent<Rigidbody>().useGravity = false;
                interactBox.GetComponent<Rigidbody>().isKinematic = true;
            }
        }
        //松开Trigger键
        if (device.GetPressUp(SteamVR_Controller.ButtonMask.Trigger))
        {
            if (interactBox != null)
            {
                interactBox.transform.parent = transform.parent.parent;
                interactBox.GetComponent<Rigidbody>().useGravity = true;
                interactBox.GetComponent<Rigidbody>().isKinematic = false;
                interactBox = null;
            }
        }
    }
    void OnTriggerEnter(Collider other)
    {
        interactBox = other.transform.gameObject;
    }
    void OnTriggerExit(Collider other)
    {
        interactBox = null;
    }
    void OnTriggerStay(Collider other)
    {
        if (device != null)
        {
            //触发震动
            device.TriggerHapticPulse(700);
        }
    }
}

原网站

版权声明
本文为[小小姑娘很大]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_55688630/article/details/128693759

随机推荐