- Home /
Vector3 Lerp finish too quicly
I am trying to write a simple script which moves the player from one position to another position.
I used a list of GameObject for the player to use these objects as the destination points.
For this I used Vector3.Lerp and an IEnumerator.
.
In documentation Lerp have a float parameter which has a range of 0 to 1;
As I understand when this parameter becomes 1 that's mean object arrives at its destination. (This is not happening in my code which is my problem)
So I tried to write a code that makes the player move to next point and when it arrives then immediately starts to make it move to the next point until there is no next point left.
//
public List<GameObject> WayPoints = new List<GameObject>();
public float speed = 10f;
private int nextWayPoint = 0;
private void Start()
{
StartCoroutine(SmoothlyShiftPosition(WayPoints[nextWayPoint].transform.position, speed));
}
IEnumerator SmoothlyShiftPosition(Vector3 destination, float OverTime)
{
nextWayPoint++;
float startTime = 0f;
while (startTime / OverTime < 1f)
{
Debug.Log(startTime / OverTime);
transform.position = Vector3.Lerp(transform.position, destination, startTime / OverTime);
startTime += Time.deltaTime;
yield return null;
}
transform.position = destination;
if (WayPoints[nextWayPoint] != null)
{
StartCoroutine(SmoothlyShiftPosition(WayPoints[nextWayPoint].transform.position, speed));
}
}
My problem is the player arrives at next point long before (startTime / OverTime) parameter becomes "1". And player waits until the parameter finally becomes "1" and then start to go to the next point.
How can I fix this?
Answer by Hellium · Aug 08, 2019 at 11:31 AM
If you use Lerp( A, B, t )
with t ∈ [0, 1], A
and B
must remain the same, however, in your current code, A
is changed every frame.
IEnumerator SmoothlyShiftPosition(Vector3 destination, float OverTime)
{
Vector3 origin = transform.position;
nextWayPoint++;
float startTime = 0f;
while (startTime / OverTime < 1f)
{
Debug.Log(startTime / OverTime);
transform.position = Vector3.Lerp(origin, destination, startTime / OverTime);
startTime += Time.deltaTime;
yield return null;
}
transform.position = destination;
if (nextWayPoint < WayPoints.Count && WayPoints[nextWayPoint] != null)
{
StartCoroutine(SmoothlyShiftPosition(WayPoints[nextWayPoint].transform.position, speed));
}
}
Thanks a lot, it worked. I should have been more careful.
Your answer
Follow this Question
Related Questions
tell me whats wrong with this lerp 1 Answer
Weapon Movement Freezing 0 Answers
Smooth translation 2 Answers
Vector3.Lerp Only working once 1 Answer
Vector3 Lerp using Time.deltaTime? 3 Answers