如何解决基于物理的飞机飞行系统问题

时间:2019-06-09 10:31:59

标签: c# unity3d game-engine

我在基于物理的飞机飞行系统中遇到问题

除了一件事外,一切都可以在我的代码中正常工作

如果飞机突然急转180度,它将开始向后飞行,大约需要十秒钟才能使飞机再次向前飞行。

我能做些什么来解决这个问题?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class Airplane : MonoBehaviour {

    public Rigidbody airplaneBody;

    [System.Serializable]
    public class AirplaneData {
        public float enginePower = 0.0f, maxSpeed = 0.0f, turnPower = 0.0f, maxTurnSpeed = 0.0f, liftPower = 0.0f;
    }
    public AirplaneData data;

    public bool freeLook = false;

    void UpdateMouse () {
        if (freeLook == true) {
            Cursor.lockState = CursorLockMode.None;
            Cursor.visible = true;
        } else if (freeLook == false) {
            Cursor.lockState = CursorLockMode.Locked;
            Cursor.visible = false;
        }
    }
    void Update () {
        UpdateMouse ();
        if (Input.GetKeyDown (KeyCode.F) && freeLook == false) {
            freeLook = true;
        } else if (Input.GetKeyDown (KeyCode.F) && freeLook == true) {
            freeLook = false;
        }
    }
    void FixedUpdate () {
        if (airplaneBody != null) {
            AirplaneControls ();
        }
        airplaneBody.AddRelativeForce (0, data.liftPower * airplaneBody.velocity.magnitude, 0);
        if (airplaneBody.velocity.magnitude > data.maxSpeed) {
            airplaneBody.velocity = airplaneBody.velocity.normalized * data.maxSpeed;
        }
        if (airplaneBody.angularVelocity.magnitude > data.maxTurnSpeed) {
            airplaneBody.angularVelocity = airplaneBody.angularVelocity.normalized * data.maxTurnSpeed;
        }
    }
    void AirplaneControls () {
        if (airplaneBody != null) {
            if (Input.GetKey (KeyCode.W)) {
                airplaneBody.AddRelativeForce (0, 0, data.enginePower);
            }
            if (Input.GetKey(KeyCode.A)) {
                airplaneBody.AddRelativeTorque (0, -data.turnPower * airplaneBody.velocity.magnitude, 0);
            } else if (Input.GetKey (KeyCode.D)) {
                airplaneBody.AddRelativeTorque (0, data.turnPower * airplaneBody.velocity.magnitude, 0);
            }
            if (freeLook == false) {
                airplaneBody.AddRelativeTorque (0, 0, Input.GetAxis ("Mouse X") * -data.turnPower * 10);
                airplaneBody.AddRelativeTorque (Input.GetAxis ("Mouse Y") * data.turnPower * 10, 0, 0);
            }
        }
    }

}

1 个答案:

答案 0 :(得分:1)

我看不到您在考虑速度矢量时考虑到飞机的前向矢量。

顺便说一句,这个:

<script>
  function ready() {
    for(var j=1;j<32;j++)document.write("<option value="+j+">"+j+"</option>");
  }

  document.addEventListener("DOMContentLoaded", ready);
</script>

可以表示为:

 if (Input.GetKeyDown (KeyCode.F) && freeLook == false) {
            freeLook = true;
        } else if (Input.GetKeyDown (KeyCode.F) && freeLook == true) {
            freeLook = false;
        }

'!'将布尔值从true变为false,反之亦然。