Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

vector

unity3d

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);
}
like image 756
Mingan Beyleveld Avatar asked Nov 30 '14 10:11

Mingan Beyleveld


1 Answers

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;
    }
}
like image 98
Lokkij Avatar answered Sep 22 '22 05:09

Lokkij