本文简单实现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();
}
}
}
这样就可以实现自由飞行,而且不会受到加速度的影响了。