- Home /
Smooth movement between waypoints 2D
Hi, I'm trying to achieve smooth movement between Vector2 waypoints (in 2D) without either jumping ahead or "lagging" behind because for 2 frames you can move to the same spot while the waypoints are being swapped. I've been struggling with the logic required for it for the past 2 days now.
This is my code:
t += Time.deltaTime * speed;
float nextFrame;
Vector2 nextFramePosition;
if (t < 1f)
{
transform.position = Vector2.Lerp(wayPointList[0], wayPointList[1], t);
nextFrame = t + Time.deltaTime * speed;
nextFramePosition = Vector2.Lerp(wayPointList[0], wayPointList[1], nextFrame);
if (nextFramePosition == wayPointList[1])
{
t = 0;
transform.position = Vector2.Lerp(wayPointList[0], wayPointList[1], nextFrame);
endOfWaypoint = true;
}
}
In the part where I "predict" the position in the next frame I can either set that position early (which causes a jump ahead to the waypoint) or If I don't it will still jump ahead on the next frame because t will be higher than 0 so it has a head start. And if I change the speed to a higher value the "head start" is even higher which is expected but not desirable.
Is there a spesific technique to tackle something like that ? And yes I am aware of the assets that can offer that but I'm trying to write my own implemetation.
Answer by eses · Aug 26, 2018 at 01:27 PM
Hi @Noshiz
You description doesn't make Lerping sound like a good choice. If your target can change at any moment, why not just make your movement based on MoveTowards?
See manual for example:
https://docs.unity3d.com/ScriptReference/Vector3.MoveTowards.html
Your suggestion was actually good. Reworked a bit the code and the movement is much smoother now.
if (Vector2.Distance(transform.position, wayPointList[0]) <= 0.5)
{
endOfWaypoint = true;
}
if (endOfWaypoint)
{
endOfWaypoint = false;
wayPointList.RemoveAt(0);
}
transform.position = Vector2.$$anonymous$$oveTowards(this.transform.position, wayPointList[0], Time.deltaTime * speed);
I'm checking the distance now ins$$anonymous$$d of the exact positions and move on to the next waypoint based on that. I am however wondering how well that will work with curves.
ok good - if the answer is correct, consider marking it as accepted / best answer. Thanks
Your answer
![](https://koobas.hobune.stream/wayback/20220612173522im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
2D smooth top-down movement 1 Answer
Unity 2D - Smooth movement over tiles?? 1 Answer
Complex 2D movement (X,Y) using velocity. 1 Answer
Android 2d movement/waypoint script issues 0 Answers
Smooth Character Movement 1 Answer