Htc vive 实现简单飞行

本文简单实现Htc vive 飞行,左手控制上,下,右手控制头盔向面朝前方前进。

本教程使用插件vrtk脚本,左右手都需要先挂脚本VRTK_ControllerEvents。

首先创建一个Fly脚本作为父类控制Rigidbody.isKinematic的开关:

public class Fly : MonoBehaviour {

    [HideInInspector]
    public bool isKem;

  
    public bool GetRig() {//Kem赋值
        var flies = FindObjectsOfType<Fly>();//获取场景下所有继承Fly的子类对象

        bool Kem = true;

        foreach (var temp in flies) {
            if (temp.isKem == false) {//其中一个子类的isKem为false 则Kem为false;
                Kem = false;
                break;
            }
        }

        return Kem;
    }
}

右手柄挂在脚本如下,


public class FlyLevel : Fly {

    public VRTK_ControllerEvents controller;//手柄 右

    public GameObject Hmd;//头盔

    public Transform Eye;//头盔眼镜

	
	// Update is called once per frame
	void Update () {
        if (controller.gripTouched)
        {
            Hmd.GetComponent<Rigidbody>().isKinematic = false;
            Hmd.GetComponent<Rigidbody>().AddForce(new Vector3((Eye.forward.x) * 10, 0, (Eye.forward.z) * 10));//施加forword的力
            isKem = false;
        }
        else
        {
            isKem = true;
            Hmd.GetComponent<Rigidbody>().isKinematic = GetRig();
        }
    }
}

左手柄挂在脚本如下:


public class FlyHigh : Fly {

    public VRTK_ControllerEvents controller;//控制手柄 左

    public GameObject Hmd;//头盔

  
	// Update is called once per frame
	void Update () {
        if (controller.triggerTouched) {//触碰扳机
            
            Hmd.GetComponent<Rigidbody>().isKinematic = false;
            Hmd.GetComponent<Rigidbody>().AddForce(new Vector3(0, 10f, 0));//施加向上的力
            isKem = false;
        }
        else if (controller.gripTouched) {//施加向下的力
            Hmd.GetComponent<Rigidbody>().isKinematic = false;
            Hmd.GetComponent<Rigidbody>().AddForce(new Vector3(0, -10f, 0));
            isKem = false;
        }
        else//什么都不按
        {
            isKem = true;
            Hmd.GetComponent<Rigidbody>().isKinematic = GetRig();
        }
    }
}

这样就可以实现自由飞行,而且不会受到加速度的影响了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值