Hello, Object is moving by MoveTowards(transform.position, points[index], speed). But sometimes on path I have a larger cluster of points, thus the object slows down. As you can see on picture, object a will be faster than object b, they are moving with the same *speed. What can I do to make object not slowing down where points will be more? I know why it slow down but I dont know what can I use instead movetowards. I tried with lookat and transform translate with vector3.forward but with faster speed object starts to lose because it jumps over more than one point during one frame.
MoveTowards on paths, different speeds
Asked Answered
[Unity - Scripting API: Vector3.MoveTowards][1]
As you can read in the documentation:
If the target is closer than
maxDistanceDelta
then the returned value will be equal to target (ie, the movement will not overshoot the target).
When your object approaches the next target point, it will only move as far as its target point, even if it’s speed should move it farther.
If you want your object to move with a constant speed, you should compare the distance you want your object to move with the distance it has really moved. If the travelled distance is lower than expected, move it to the next target using the remaining distance as the maxDistanceDelta
parameter. Something like this should work:
float distanceTravelled;
Vector3 currentPosition;
Vector3 nextPosition;
...
nextPosition = Vector3.MoveTowards(currentPosition, target*, speed);*
_if (nextPosition == target*) {*_
<em>_distanceTravelled = Vector3.Distance(currentPosition, target*);*_</em>
<em>_*target++;*_</em>
<em>_*if (distanceTravelled < speed) {*_</em>
<em><em>_nextPosition = Vector3.MoveTowards(nextPosition, target*, speed - distanceTravelled);*_</em></em>
<em><em>_*}*_</em></em>
<em><em>_*}*_</em></em>
<em><em>_*currentPosition = nextPosition;*_</em></em>
<em><em>_*obj.transform.position = currentPosition;*_</em></em>
<em><em>_*```*_</em></em>
<em><em>_*If your path has points packed so densely your object moves more than 2 points at a time, you can put that code in a while loop, iterating until the total travelled distance isn't greater or equal to your speed.*_</em></em>
<em><em>_*[1]: https://docs.unity3d.com/ScriptReference/Vector3.MoveTowards.html*_</em></em>
© 2022 - 2025 — McMap. All rights reserved.
Thank you for explanation and example! Works very well, I did it in a loop, in case of speed was greater than the distance between more than two points because on curves I have very densely placed points
– Geller