VR開發中HTC的手柄控制按鍵設置(1)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 定義一個手柄上按鍵控制的類
/// </summary>
public class ButtonTouchAction : MonoBehaviour {
    SteamVR_TrackedObject trackedObjec;
    // Use this for initialization
    void Start () {
        //獲取手柄輸入
        trackedObjec = GetComponent<SteamVR_TrackedObject>();
    }

    // Update is called once per frame
    void Update () {

    }
    void FixedUpdate()
    {
        //獲取手柄輸入
        SteamVR_Controller.Device device = SteamVR_Controller.Input((int)trackedObjec.index);
        //當按下扳機時   
        if (device.GetTouchDown(SteamVR_Controller.ButtonMask.Trigger))
        {
            print("按下了扳機");
        }
        //當按下手柄上的圓盤鍵時
        if (device.GetPress(SteamVR_Controller.ButtonMask.Touchpad))
        {
            // 獲取觸摸板上的座標
            Vector2 pad = device.GetAxis();
            // 轉換角度
            Vector3 cross = Vector3.Cross(new Vector2(1, 0), pad);
            float angle = Vector2.Angle(new Vector2(1, 0), pad);
            //三目運算 z>0是-angle 否則是angle
            float ang = cross.z > 0 ? -angle : angle;
            //根據角度來判斷上下左右四個範圍
            //下
            if (ang > 45 && ang < 135)
            {
                print("下");
                hero.transform.Translate(Vector3.back * moveSpeed * Time.deltaTime);
            }
            //上  
            else if (ang < -45 && ang > -135)
            {
                print("上");
                hero.transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);
            }
            //左  
            else if ((ang < 180 && ang > 135) || (ang < -135 && ang > -180))
            {
                print("左");
                hero.transform.Rotate(Vector3.up * -rotateSpeed * Time.deltaTime);
            }
            //右  
            else if ((ang > 0 && ang < 45) || (ang > -45 && ang < 0))
            {
                print("右");
                hero.transform.Rotate(Vector3.up * rotateSpeed * Time.deltaTime);
            }
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章