Slowly moving an object to a new position in Unity C#

25,398

Solution 1

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;
    }
}

Solution 2

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;
Share:
25,398
Mingan Beyleveld
Author by

Mingan Beyleveld

Updated on July 29, 2020

Comments

  • Mingan Beyleveld
    Mingan Beyleveld almost 4 years

    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);
    }