VRTK经典案例13演示了如何实现手枪射击效果,场景如图
分析手柄,包含了如下图所示的组件
分析场景中的手枪模型,包含了如下图所示的组件
分析其中的Gun脚本,源码如下
namespace VRTK.Examples
{
using UnityEngine;
public class Gun : VRTK_InteractableObject
{
private GameObject bullet;
private float bulletSpeed = 1000f;
private float bulletLife = 5f;
public override void StartUsing(VRTK_InteractUse usingObject)
{
base.StartUsing(usingObject);
FireBullet();
}
protected void Start()
{
bullet = transform.Find("Bullet").gameObject;
bullet.SetActive(false);
}
private void FireBullet()
{
GameObject bulletClone = Instantiate(bullet, bullet.transform.position, bullet.transform.rotation) as GameObject;
bulletClone.SetActive(true);
Rigidbody rb = bulletClone.GetComponent<Rigidbody>();
rb.AddForce(-bullet.transform.forward * bulletSpeed);
Destroy(bulletClone, bulletLife);
}
}
}
要点就是继承自VRTK_InteractableObject,重写StartUsing方法实现对自定义方法 FireBullet()的调用。