unity2d, дрожание предсказания траектории - PullRequest
0 голосов
/ 10 марта 2020

Я делаю мобильную игру, которая использует траекторию, чтобы узнать следующий путь от моего игрока. Когда игрок молчит, траектория работает очень хорошо, но когда игрок движется, траектория иногда перемещается сама по себе, хотя позже она возвращается в правильное положение, но это очень мешает. Вот сценарий:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class PlayerMovement : MonoBehaviour
{
    public static PlayerMovement Instance;

    Rigidbody2D rb;

    Vector3 startPos;
    Vector3 endPos;
    [HideInInspector] public Vector3 initPos;

    [HideInInspector] public Vector3 direction;
    public static Vector3 anotherSpeed;  // Only for trajectory
    float speedMultiplier = 1.5f;

    public GameObject trajectoryDot;
    GameObject[] trajectoryDots;
    public int numbersOfTrajectory;
    float trajectoryDotsDistance = 0.001f;

    public static float energy = 100f;
    public Slider energyBar;

    float slowDownFactor = 0.3f;

    private void Start()
    {
        if (!Instance)
            Instance = this;

        rb = GetComponent<Rigidbody2D>();

        trajectoryDots = new GameObject[numbersOfTrajectory];
    }

    void Update()
    {
        anotherSpeed = direction;

        if (!Pause.isPaused)
        {
            // Get Start Position
            if (Input.GetMouseButtonDown(0))
            {

                // Instansiate The Trajectory
                for (int i = 0; i < numbersOfTrajectory; i++)
                {
                    trajectoryDots[i] = Instantiate(trajectoryDot,gameObject.transform.position, gameObject.transform.rotation);
                }
            }

            // Get Position When Dragging
            if (Input.GetMouseButton(0))
            {
                EnableSlowMotion();

                // Get Drag Position
                endPos = Camera.main.ScreenToWorldPoint(Input.mousePosition) + new Vector3(0, 0, 10);

                startPos = gameObject.transform.position;

                // Get The Speed

                direction = endPos - startPos;
                direction = direction.normalized;
                direction = Vector3.Lerp(transform.position, direction, 500 * Time.deltaTime);
                direction = direction * 18;

                // Update The Trajectory Position
                for (int i = 0; i < numbersOfTrajectory; i++)
                {
                    trajectoryDots[i].transform.position = calculatePosition(i * trajectoryDotsDistance);
                }
            }

            // Get Position When Realeasing
            if (Input.GetMouseButtonUp(0))
            {

                DisableSlowMotion();

                // enable Gravity
                rb.gravityScale = 1f;

                // Move The Player
                rb.velocity = new Vector2(direction.x * speedMultiplier, direction.y * speedMultiplier);


                // Destroy The Trajectory When Player Release
                for (int i = 0; i < numbersOfTrajectory; i++)
                {
                    Destroy(trajectoryDots[i]);
                }
            }

        }

        CameraZoom();
        ControlsChecker();
    }


    // Calculate The Trajectory Prediction 
    Vector2 calculatePosition(float elapsedTime)
    {
        return new Vector2(startPos.x, startPos.y) +
               new Vector2(anotherSpeed.x * speedMultiplier, anotherSpeed.y * speedMultiplier) * elapsedTime +
                0.5f * Physics2D.gravity * elapsedTime * elapsedTime;
    }



    // Check Controls Is pull or push 
    void ControlsChecker()
    {
        if (PlayerPrefs.GetInt("Controls") == 1)
        {
            direction = direction;
            anotherSpeed = anotherSpeed;
        }
        else
        {
            direction = -direction;
            anotherSpeed = -anotherSpeed;
        }
    }


    void EnableSlowMotion()
    {
        Time.timeScale = slowDownFactor;
        Time.fixedDeltaTime = 0.02f * Time.timeScale;
    }

    void DisableSlowMotion()
    {
        Time.timeScale = 1f;
        Time.fixedDeltaTime = 0.02F;
    }
}


void CameraZoom()
{
        if (Input.GetMouseButton(0))
        {
            vcam.m_Lens.OrthographicSize += 0.1f;
            if (vcam.m_Lens.OrthographicSize >= maxZoom)
            {
                vcam.m_Lens.OrthographicSize = maxZoom;
            }
        }
        else if (Input.GetMouseButtonUp(0))
        {
            zoomIn = true;
        }

        if (zoomIn)
        {
            vcam.m_Lens.OrthographicSize -= 0.2f;
            if (vcam.m_Lens.OrthographicSize <= minZoom)
            {
                vcam.m_Lens.OrthographicSize = minZoom;
                zoomIn = false;
            }
        }
}



, поэтому я получаю направление движения игрока из расчета, основанного на точке, где я касаюсь, и точке, когда я отпускаю касание (перетаскивание). Я сделал ошибку в коде, который часто вызывал вибрацию моей траектории? Мне действительно нужна помощь, спасибо заранее.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...