Попытка сделать поезд в Unity, но возникли некоторые проблемы - PullRequest
0 голосов
/ 19 февраля 2019

Так что, привет, ребята.Я пытаюсь сделать поезд в Unity.Я создал пустые объекты с кубиками, которые содержат данные Transforms, на которые должен ехать поезд.Все работает хорошо, но у меня такая проблема.Во время езды поезд несколько раз «дергается», и я действительно не могу понять, почему это происходит.Если кто-то может помочь, что делать, я буду очень рад услышать ваши ответы.

TrainMovement.cs

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

public class NewTrainMovemnt : MonoBehaviour 
{

    public GameObject waypointContainer;
    public AnimationCurve startCurve;
    private Vector3[] waypoints = new Vector3[30];
    public int currentWaypoint = 0;
    public float speed = 0.0F;
    public float currentSpeed;
    public int direction = 0;
    public int acceleration = 0;
    public float acc = 0;
    private float startTime;
    public Vector3 movementVector;
    public float damping;

    // Use this for initialization
    void Start () 
    {
        for (int i = 0; i < waypointContainer.transform.childCount; i++) 
        {
            waypoints[i] = waypointContainer.transform.GetChild(i).transform.position;
            Debug.Log(waypoints[i]);
        }
    }

    void FixedUpdate () 
    {
        if (Input.GetKeyDown ("e")) 
        {
            acceleration++;
        }

        if (Input.GetKeyDown ("q")) 
        {
            acceleration--;
        }

        if (acceleration==-1)
            acc=-0.001F;
        if (acceleration==-2)
            acc=-0.002F;
        if (acceleration==-3)
            acc=-0.003F;
        if (acceleration < -3) 
        {
            acceleration = -3;
        }
        if (acceleration==0)
            acc=0.0F;
        if (acceleration==1)
            acc=0.001F;
        if (acceleration==2)
            acc=0.002F;
        if (acceleration==3)
            acc=0.003F;
        if (acceleration > 3) 
        {
            acceleration = 3;
        }

        for (int i = 0; i < waypointContainer.transform.childCount; i++) 
        {
            MoveToWaypoint();
            startTime = Time.time + 2.0F;
        }
    }

    void MoveToWaypoint() 
    {
        currentSpeed += startCurve.Evaluate((Time.time - startTime)/10)*acc;

        float currentStep = currentSpeed * Time.smoothDeltaTime;

        movementVector = Vector3.MoveTowards(this.transform.position, waypoints[currentWaypoint], currentStep);
        Debug.Log(movementVector);
        float distance = Vector3.Distance(this.transform.position, movementVector);
        float distance_ = Vector3.Distance(this.transform.position, waypoints[currentWaypoint]);

        if (currentStep - distance > 0.001) 
        {
            currentWaypoint += direction;
            if (currentWaypoint >= 0 && currentWaypoint < waypointContainer.transform.childCount) 
            {
                movementVector = Vector3.MoveTowards(this.transform.position,waypoints[currentWaypoint], currentStep);
            }

            if (distance_ == 0f) 
            {
                currentWaypoint++;
            }
        }
    }


    // Update is called once per frame
    void Update () 
    {
        this.transform.position = movementVector;

        damping = 3.5f;

        Quaternion rotation = Quaternion.LookRotation(waypoints[currentWaypoint] - this.transform.position);
        this.transform.rotation = Quaternion.Slerp(this.transform.rotation, rotation, Time.deltaTime * damping);
    }
}

Пример "извилистости": https://youtu.be/7xVMVrxbbgw

1 Ответ

0 голосов
/ 20 февраля 2019

Как указано выше, ввод не должен выполняться в цикле FixedUpdate ().Это для расчета физики.

Чтобы исправить Twitching, я бы посоветовал убрать эти проверки ввода из фиксированного обновления, отменить перемещение между узлами и изменить этот большой блок IF на оператор Switch.Делать все это в обновлениях очень неэффективно.

...