Как я могу всегда перемещать свой объект в зависимости от направления моей оси?

Я пытаюсь переместить свой мяч на фиксированное расстояние. Для этого я использовал Vector3 и Lerping.

Но когда мой объект вращается, шар все еще движется в том же направлении, а не в новом направлении, заданном моим направлением оси X.

public float timeTakenDuringLerp = 1f;

/// <summary>
/// How far the object should move when 'UpArrow' is pressed
/// </summary>
public float distanceToMove = 7; //value can be change in unity

//Whether we are currently interpolating or not
private bool _isLerping;

//The start and finish positions for the interpolation
private Vector3 _startPosition;
private Vector3 _endPosition;

//The Time.time value when we started the interpolation
private float _timeStartedLerping;
Vector3 myVector;

/// <summary>
/// Called to begin the linear interpolation
/// </summary>

void StartLerping1()
{
    _isLerping = true;
    _timeStartedLerping = Time.time;

    //We set the start position to the current position, and the finish to 7 spaces in the 'forward' direction
    _startPosition = transform.position;

    myVector = new Vector3(1, 0, 0);
    _endPosition = transform.position + myVector * distanceToMove;
}

void Update()
{
    //When the user hits the up arrow, we start lerping
    if (Input.GetKey(KeyCode.UpArrow))
    {
        StartLerping1();
    }

    if (Input.GetKeyDown(KeyCode.RightArrow))
    {
        // THE ROTATION IS SUPPOSED TO HAPPEN, AND THE MOVEMENT SHOULD BE BASED ON THIS NEW DIRECTION
    }

}

// Мы делаем фактическую интерполяцию в FixedUpdate(), так как мы имеем дело с vid твердого тела FixedUpdate() { if (_isLerping) { // Мы хотим, чтобы процент = 0,0, когда Time.time = _timeStartedLerping // и процент = 1,0, когда Time.time = _timeStartedLerping + timeTakenDuringLerp // Другими словами, мы хотим знать, каков процент "timeTakenDuringLerp" значения //"Time.time - _timeStartedLerping". float timeSinceStarted = Time.time - _timeStartedLerping; float процент Complete = timeSinceStarted / timeTakenDuringLerp;

        //Perform the actual lerping.  Notice that the first two parameters will always be the same
        //throughout a single lerp-processs (ie. they won't change until we hit the space-bar again
        //to start another lerp)
        transform.position = Vector3.Lerp(_startPosition, _endPosition, percentageComplete);

        //When we've completed the lerp, we set _isLerping to false
        if (percentageComplete >= 1.0f)
        {
            _isLerping = false;
        }
    }
}

1 ответ

Решение

Когда ты сказал

myVector = new Vector3(1, 0, 0); //you can short hand to myVector = Vector3.right

Вы объявляете вектор, указывающий вправо (да, (1, 0, 0) - это право, а не вперед) в мировом пространстве, в качестве единого целевого элемента Unity будет использоваться эта маленькая ось в правом верхнем углу в представлении сцены. движение,

который не изменится при вращении.

то, что вы хотите сделать, это использовать преобразование GameObject в качестве ссылки, это локальная пространственная координата, которая принимает во внимание вращение, а не

myVector = Vector3.forward;

пытаться

myVector = transform.forward;

и применить движение в этом направлении.

Другие вопросы по тегам