VR开发--HTCVive基础(3):小项目制作

1、项目搭建

导入素材,添加相关SDK

2、给物体修改tag,给手柄绑定刚体组件

VR开发--HTCVive基础(3):小项目制作_第1张图片
Paste_Image.png

3、脚本

  // 检测手柄指向物体或离开物体
    SteamVR_LaserPointer l;
    // 手柄事件系统
    SteamVR_TrackedController t;
    Transform pointT;
    GameObject currentCatch;
    void Start () {

        l = GetComponent();
        l.PointerIn += PointerIn;
        l.PointerOut += PointerOut;

        t = GetComponent();
        t.TriggerClicked += TriggerClicked;
        t.TriggerUnclicked += TriggerUnclicked;
    }
    
    void PointerIn(object sender, PointerEventArgs e)
    {
        if (e.target.gameObject.tag == "Super")
        {
            pointT = e.target;
        }
    }
    void PointerOut(object sender, PointerEventArgs e)
    {
        pointT = null;
    }
    void TriggerClicked(object sender, ClickedEventArgs e)
    {
        if (pointT == null)
        {
            return;
        }
        pointT.position = this.transform.position;
        pointT.gameObject.AddComponent().connectedBody = this.GetComponent();
        currentCatch = pointT.gameObject;
    }
    void TriggerUnclicked(object sender, ClickedEventArgs e)
    {
        if (currentCatch == null)
        {
            return;
        }
        var device = SteamVR_Controller.Input((int)this.GetComponent().index);
        device.TriggerHapticPulse(2800);
        // 松开将速度传递给物体
        currentCatch.GetComponent().velocity = device.velocity * 5;
        currentCatch.GetComponent().angularVelocity = device.angularVelocity;
        Destroy(currentCatch.GetComponent();
        currentCatch = null;

    }
VR开发--HTCVive基础(3):小项目制作_第2张图片
Paste_Image.png

4、实现子弹发射功能

public class TrackedController_shoot : 
SteamVR_TrackedController {
        void Start () {
        base.Start();
    }
    
    void Update () {
        base.Update();
    }

 public override void OnTriggerClicked(ClickedEventArgs e)
    {
        GameObject go = GameObject.CreatePrimitive(PrimitiveType.Sphere);
        go.transform.position = this.gameObject.transform.position;
        go.transform.localScale = new Vector3(0.1f,0.1f,0.1f);
        go.AddComponent().AddForce(this.transform.forward * 100);
        go.tag = "Super";
    }
}

你可能感兴趣的:(VR开发--HTCVive基础(3):小项目制作)