7

I have a car object in my scene. I would like to simulate a basic driving animation by moving it to a new position slowly... I have used the code below but I think I'm using Lerp wrong? It just jumps forward a bit and stops?

void PlayIntro() {
    GameObject Car = carObject;
    Vector3 oldCarPos = new Vector3(Car.transform.position.x, Car.transform.position.y, Car.transform.position.z);
    GameObject posFinder = GameObject.Find("newCarPos");

    Vector3 newCarPos = new Vector3(posFinder.transform.position.x, posFinder.transform.position.y, posFinder.transform.position.z);

    carObject.transform.position = Vector3.Lerp (oldCarPos, newCarPos, Time.deltaTime * 2.0f);
}
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Mingan Beyleveld
  • 281
  • 2
  • 5
  • 19

2 Answers2

12

There's two problems with your code:

  • Vector3.Lerp returns a single value. Since your function will only be called once, you're just setting the position to whatever Lerp returns. You will want to change the position every frame instead. To do this, use coroutines.

  • Time.DeltaTime returns the time that has passed since the last frame, which will generally be a very small number. You will want to pass in a number ranging from 0.0 to 1.0 depending the progress of the movement.

Your code will then look like this:

IEnumerator MoveFunction()
{
    float timeSinceStarted = 0f;
    while (true)
    {
        timeSinceStarted += Time.DeltaTime;
        obj.transform.position = Vector3.Lerp(obj.transform.position, newPosition, timeSinceStarted);

        // If the object has arrived, stop the coroutine
        if (obj.transform.position == newPosition)
        {
            yield break;
        }

        // Otherwise, continue next frame
        yield return null;
    }
}
Lokkij
  • 424
  • 4
  • 15
1

A simple solution is immediately after the Lerp function actually set the object's position to the desired position

here's what it should look like

carObject.transform.position = Vector3.Lerp (oldCarPos, newCarPos, Time.deltaTime * 2.0f);
carObject.transform.position = newCarPos;
Matt
  • 11
  • 1
  • Hi @Matt, the code is working fine but this way the gameobject moves to fast, Do you know how can I make the movement slowly? I've already tried changing the value 2.0f from (Time.deltaTime * 2.0f). Thanks in advance – Zilev av Sep 17 '16 at 02:03