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

2020-06-02 17:01:56 浏览数 (1)

1、项目搭建

导入素材,添加相关SDK

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

Paste_Image.png

3、脚本
代码语言:javascript复制
  // 检测手柄指向物体或离开物体
    SteamVR_LaserPointer l;
    // 手柄事件系统
    SteamVR_TrackedController t;
    Transform pointT;
    GameObject currentCatch;
    void Start () {

        l = GetComponent<SteamVR_LaserPointer>();
        l.PointerIn  = PointerIn;
        l.PointerOut  = PointerOut;

        t = GetComponent<SteamVR_TrackedController>();
        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<FixedJoint>().connectedBody = this.GetComponent<Rigidbody>();
        currentCatch = pointT.gameObject;
    }
    void TriggerUnclicked(object sender, ClickedEventArgs e)
    {
        if (currentCatch == null)
        {
            return;
        }
        var device = SteamVR_Controller.Input((int)this.GetComponent<SteamVR_TrackedObject>().index);
        device.TriggerHapticPulse(2800);
        // 松开将速度传递给物体
        currentCatch.GetComponent<Rigidbody>().velocity = device.velocity * 5;
        currentCatch.GetComponent<Rigidbody>().angularVelocity = device.angularVelocity;
        Destroy(currentCatch.GetComponent<FixedJoint>();
        currentCatch = null;

    }

Paste_Image.png

4、实现子弹发射功能
代码语言:javascript复制
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<Rigidbody>().AddForce(this.transform.forward * 100);
        go.tag = "Super";
    }
}

0 人点赞