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

发布于:2022-12-23 ⋅ 阅读:(417) ⋅ 点赞:(0)

在这里插入图片描述

目录

🟥 实现目标:

🟧 实现步骤


🟥 实现目标:

手柄碰触盒子时,扣动扳机键,拿起盒子(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);
        }
    }
}

大家还有什么问题,欢迎在下方留言!


 

在这里插入图片描述


如果你有 技术的问题 或 项目开发

都可以加下方联系方式

和我聊一聊你的故事🧡


网站公告

今日签到

点亮在社区的每一天
去签到