Попытка заставить самолет потерять скорость при подъеме на крутой угол и увеличить при спуске под крутым углом - PullRequest
0 голосов
/ 20 января 2020

Поэтому я пытаюсь заставить свой самолет набирать скорость при уменьшении высоты и терять ее при подъеме.

using UnityEngine;
using UnityEngine.UI;
using System;
using System.Collections;
using Random = UnityEngine.Random;

[RequireComponent(typeof(Rigidbody))]
public class Movement : MonoBehaviour
{
    public float AmbientSpeed = 400.0f;

    public float RotationSpeed = 275.0f;

    private Rigidbody _rigidBody;
    bool IsInputEnabled = true;

    void Start()
    {
        _rigidBody = GetComponent<Rigidbody>();
    }

    void Update()
    {
        if (IsInputEnabled)
        {
            // Slow down
            if (Input.GetKey("z"))
            {
                AmbientSpeed--;
                if (AmbientSpeed < 0)
                    AmbientSpeed = 0;
            }

            // Speed up
            if (Input.GetKey("x"))
            {
                AmbientSpeed++;
                if (AmbientSpeed > 400) 
                    AmbientSpeed = 400;
            }
        }
    }

    void FixedUpdate()
    {
        Quaternion AddRot = Quaternion.identity;
        float roll = 0;
        float pitch = 0;
        float yaw = 0;
        bool stall = false;

        // Getting pitch angle 
        var right = transform.right;
        right.y = 0;
        right *= Mathf.Sign(transform.up.y);
        var fwd = Vector3.Cross(right, Vector3.up).normalized;
        float pitch_rot = Vector3.Angle(fwd, transform.forward) * Mathf.Sign(transform.forward.y);

        // Engine stall
        if (IsInputEnabled)
        {
            Quaternion targetpos = new Quaternion(0.5f, AddRot.y, AddRot.z, AddRot.w);
            if (AmbientSpeed < 25)
            {
                transform.rotation = Quaternion.RotateTowards(transform.rotation, targetpos, 50 * Time.deltaTime);
            }

            if (stall == true && AmbientSpeed == 0 && AmbientSpeed < 100)
            {
                if (AmbientSpeed < 100)
                {
                    AmbientSpeed = AmbientSpeed + 1;
                }
                if (AmbientSpeed > 100)
                {
                    stall = false;
                }
            }
        }

        if (IsInputEnabled)
        {
            roll = Input.GetAxis("Roll") * (Time.fixedDeltaTime * RotationSpeed);
            pitch = Input.GetAxis("Pitch") * (Time.fixedDeltaTime * RotationSpeed);
            yaw = Input.GetAxis("Yaw") * (Time.fixedDeltaTime * RotationSpeed);
            AddRot.eulerAngles = new Vector3(-pitch, yaw, -roll);
            _rigidBody.rotation *= AddRot;
            Vector3 AddPos = Vector3.forward;
            AddPos = _rigidBody.rotation * AddPos;
            _rigidBody.velocity = AddPos * (Time.fixedDeltaTime * AmbientSpeed);

            if (Vector3.Dot(transform.up, Vector3.down) > 0)
            {
                _rigidBody.AddForce(0, 0, -10);
            }

            if (pitch_rot > 30)
            {
                AmbientSpeed = AmbientSpeed - 0.001f;

                if (AmbientSpeed < 0)
                {
                    AmbientSpeed = 0f;
                }
            }

            if (pitch_rot > 50 && AmbientSpeed < 200)
            {
                AmbientSpeed = AmbientSpeed - 10;
                if (AmbientSpeed < 0)
                {
                    AmbientSpeed = 0;
                    stall = true;
                }
                Debug.Log("Stalling");
            }
        }
    }
}

Вот мой код в C# Детали, используемые для движения, находятся в FixedUpdate. Просто запутался, как получить плавное увеличение / уменьшение AmbientSpeed при крутых углах. Любая помощь приветствуется. Я новичок в Unity и c#, извините, если код немного загроможден.

Вот код с моей попыткой комментирования, не уверенный, насколько они будут полезны, так как много кода просто взято с форума и документа API страницы сценария.

using UnityEngine;
using UnityEngine.UI;
using System;
using System.Collections;
using Random = UnityEngine.Random;

[RequireComponent(typeof(Rigidbody))]
public class Movement : MonoBehaviour
{

    // Declare the max values
    public float AmbientSpeed = 400.0f;

    public float RotationSpeed = 275.0f;

    private Rigidbody _rigidBody;
    bool IsInputEnabled = true; //used in engine stall 

    void Start()
    {
        _rigidBody = GetComponent<Rigidbody>();
    }

    void Update()
    {
        if (IsInputEnabled)
        {
            // Slow down the plane when Z is held
            if (Input.GetKey("z"))
            {
                AmbientSpeed--;
                if (AmbientSpeed < 0)  // Make sure min speed isnt broken
                    AmbientSpeed = 0;
            }

            // Speed up the plane when x is held
            if (Input.GetKey("x"))
            {
                AmbientSpeed++;
                if (AmbientSpeed > 400)  // Make sure max speed isnt broken
                    AmbientSpeed = 400;
            }
        }
    }

    void FixedUpdate()
    {
        Quaternion AddRot = Quaternion.identity; // Sets current Quaternion to AddRot variable 
        float roll = 0;
        float pitch = 0;
        float yaw = 0;
        bool stall = false;

        // Getting pitch angle 
        var right = transform.right;
        right.y = 0;
        right *= Mathf.Sign(transform.up.y);
        var fwd = Vector3.Cross(right, Vector3.up).normalized;
        float pitch_rot = Vector3.Angle(fwd, transform.forward) * Mathf.Sign(transform.forward.y);  // Complex math i don't understand

        // Engine stall
        if (IsInputEnabled)
        {
            Quaternion targetpos = new Quaternion(0.5f, AddRot.y, AddRot.z, AddRot.w); // Set target pos to a declining pitch
            if (AmbientSpeed < 25)
            {
                transform.rotation = Quaternion.RotateTowards(transform.rotation, targetpos, 50 * Time.deltaTime); // when engine gets below 25 speed then rotate towards the targetpos
            }

            if (stall == true && AmbientSpeed < 100) // if we are stalling
            {

                AmbientSpeed = AmbientSpeed + 1;   // Once stall is reached and plane is in decline the speed will increase due to steep decline

                if (AmbientSpeed > 100)
                {
                    stall = false;
                }
            }
        }

        if (IsInputEnabled)
        {
            roll = Input.GetAxis("Roll") * (Time.fixedDeltaTime * RotationSpeed);
            pitch = Input.GetAxis("Pitch") * (Time.fixedDeltaTime * RotationSpeed); // User input for Pitch/roll/yaw
            yaw = Input.GetAxis("Yaw") * (Time.fixedDeltaTime * RotationSpeed);
            AddRot.eulerAngles = new Vector3(-pitch, yaw, -roll); // Sets Addrot to currect pitch/yaw/roll
            _rigidBody.rotation *= AddRot;
            Vector3 AddPos = Vector3.forward;
            AddPos = _rigidBody.rotation * AddPos; // rotates rigid body to addrot
            _rigidBody.velocity = AddPos * (Time.fixedDeltaTime * AmbientSpeed);

            if (Vector3.Dot(transform.up, Vector3.down) > 0) // If upside down then fall
            {
                _rigidBody.AddForce(0, 0, -10);
            }

            if (pitch_rot > 30)                         // If pitch too far up lose speed
            {
                AmbientSpeed = AmbientSpeed - 0.001f;

                if (AmbientSpeed < 0)
                {
                    AmbientSpeed = 0f;
                }
            }

            if (pitch_rot > 50 && AmbientSpeed < 200)        // if go too far up pitch and lose too much speed you will stall
            {
                AmbientSpeed = AmbientSpeed - 10;
                if (AmbientSpeed < 0)
                {
                    AmbientSpeed = 0;
                    stall = true; // stall is true and input will be disabled
                }
                Debug.Log("Stalling");
            }
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...