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

I have a car in my scene. I would like to simulate a basic driving animation by slowly moving it to a new position ... I used the code below, but I think I'm using Lerp incorrectly? Does he just jump a little and stop?

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); } 
+5
source share
2 answers

There are two problems in the code:

  • Vector3.Lerp returns a single value. Since your function will be called only once, you simply set the position to all Lerp . Instead, you want to reposition each frame. Use coroutines for this.

  • Time.DeltaTime returns the time elapsed since the last frame, which will usually be very small. You want to go in the range from 0.0 to 1.0 depending on the course of movement.

Then your code will 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; } } 
+8
source

A simple solution immediately after the Lerp function actually sets the position of the object to the desired position

this is what it should look like:

 carObject.transform.position = Vector3.Lerp (oldCarPos, newCarPos, Time.deltaTime * 2.0f); carObject.transform.position = newCarPos; 
0
source

Source: https://habr.com/ru/post/1207972/


All Articles