- Home /
MoveTowards on paths, different speeds
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.
Answer by LCStark · Dec 13, 2018 at 09:17 AM
https://docs.unity3d.com/ScriptReference/Vector3.MoveTowards.html
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[i], speed);
if (nextPosition == target[i]) {
distanceTravelled = Vector3.Distance(currentPosition, target[i]);
target++;
if (distanceTravelled < speed) {
nextPosition = Vector3.MoveTowards(nextPosition, target[i], speed - distanceTravelled);
}
}
currentPosition = nextPosition;
obj.transform.position = currentPosition;
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.
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
Your answer
![](https://koobas.hobune.stream/wayback/20220612183908im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Making a bubble level (not a game but work tool) 1 Answer
How to move along a few path follow ? 1 Answer
MoveTowards on paths, different speeds 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers