MoveTowards prevents overshooting

Unity - Scripting API: Vector3.MoveTowards (unity3d.com)

Unity’s built in method to solve this problem. There’s no need to calculate distance either.

var step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards( transform.position, target.position, step)

9 Likes

A good tip.

Very good tip, thanks!

Hey! I have one question about this approach.

As the step is a constant number, then the time for the movement remains constant. That means that the speed is dependant on the distance the player has to move. In other words, the further the player is from the target position, the faster its gonna move.

Is there a way to compensate for this, so that the speed is constant? Or what math operation should I do to the step to compensate?

Perhaps dividing speed by the number of units between the projectile at launch time and the target? You might then need to multiply it by a constant to make it “fast” again… like speed / initialDistance * 10;

Following the info from Unity ( moving no farther than the distance specified by maxDistanceDelta), the step is what sets how far the object moves per update.
If you times that value by Time.DeltaTime it makes it independant of framerate so the all objects should move at the same speed no matter the distance they need to travel.

Yes. I got confused and thought the speed was different.
But, indeed just using speed * Time.DeltaTime as the maxDistanceDelta is enough to keep the speed constant. And obviously the time it takes to travel will be longer, the longer the distance.

Thanks!

Privacy & Terms