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

1、项目搭建

导入素材,添加相关SDK

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

Paste_Image.png

3、脚本

  // 检测手柄指向物体或离开物体
    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、实现子弹发射功能

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";
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容