重力感應控制物件的旋轉和方向

彭然心跳發表於2018-05-17

別的不多說上乾貨

using UnityEngine;
//           玩家控制器

public class PlayerController : MonoBehaviour 
{
    //●前向推力,飛行速度的作用值之一
    public float forwardForce = 50.0f;
    //●速度比
    private float normalizedSpeed = 0.2f;
    //●UI圖示
    public Transform guiSpeedElement = null;

    //●旋轉速度
    public float turnSpeed = 10.0f;
    //●重力敏感
    public float sensitivity = 1.0f;
    //●計算用尤拉角
    private Vector3 euler = Vector3.zero;

    //●俯衝、爬升速度(飛機抬頭低頭的旋轉速度)
    private float maxTilt = 50.0f;
    //●左搖、右擺速度(飛機Z軸轉速)
    private float maxTurnLaen = 50.0f;

    void Start()
    {//■開始■
        //螢幕朝向 = 螢幕朝向.設定自動旋轉
        Screen.orientation = ScreenOrientation.AutoRotation;
        
        //更新UI座標
        float x = guiSpeedElement.position.x;
        float y = normalizedSpeed * Screen.height;
        float z = guiSpeedElement.position.z;
        guiSpeedElement.position = new Vector3(x, y, z);
    }

    void Update()
    {//■更新■
        //判斷所有觸碰點(觸碰點迭代器,遍歷觸碰點陣列)
        foreach (Touch touch in Input.touches)
        {
            //phase事件(痱子)
            if (touch.phase == TouchPhase.Moved)
            {
                //獲取觸碰
                guiSpeedElement.position = new Vector3(0, touch.position.y, 0);

                //更新速度
                normalizedSpeed = touch.position.y / Screen.height;
            }
        }//foreach
    }

    void FixedUpdate()
    {//■固定更新■
        //飛機向前飛行(位移)
        Rigidbody rb = GetComponent<Rigidbody>();
        //計算:向前力 = 比率 × 前力
        float z = normalizedSpeed * forwardForce;
        //新增相對力
        rb.AddRelativeForce(0, 0, z);

        Vector3 acc = Input.acceleration;

        //飛機的轉向(旋轉)
        //戰機X軸:爬升與俯衝(低頭抬頭),受手機Y軸影響
        euler.x = Mathf.Lerp(euler.x, Input.acceleration.y * maxTilt, .2f);
        //戰機Y軸:左轉與右轉,受手機X軸影響
        euler.y += Input.acceleration.x * turnSpeed;
        //戰機Z軸:左右傾斜,受手機負X軸影響;位移飛機之後,故取逆
        euler.z = Mathf.Lerp(euler.z, -(Input.acceleration.x * maxTurnLaen), 0.2f);
        //四元數線性差值,更新旋轉角度
        //a原始角度  b新角度  t敏感度
        transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(euler), sensitivity);
    }


}

 

相關文章