- Home /
How can I reduce speed of an object, the more that object gets close to target?
I have an Transform approaching a target Object. I want this transform's speed to be reduced to zero in a logarithmic manner, the closer it gets to that object.
Any idea how I could do that?
need more information about how speed is reduced: Should there be a general speed limit at a given distance, or should current speed slow down by a certain amount every frame, based on distance to target, or should speed only decrease when it is moving closer to the target, etc...? Is speed relative to the target, or a global speed.
Answer by Dave-Carlile · Oct 01, 2015 at 04:51 PM
The approach I usually take for things like this is to map the range of values I want into a range from 0 to 1. That value gets plugged into my function to produce the value I want. This is the same concept used by Lerp and similar functions.
To map your distance to the 0-1 range you could do this...
float maxDistance = 100.0f; // the range at which you want to start slowing
float percentageOfMax = Vector3.Distance(moving_object, target_object) / maxDistance;
// clamp the value to 0-1 so we don't have to do a comparison
percentageOfMax = Mathf.Clamp01(percentageOfMax);
// if you were using lerp to change the speed...
float speed = Mathf.Lerp(min_speed, max_speed, percentageOfMax);
You would just need to replace Lerp with your logarithmic interpolation function. That's left as an exercise for the reader 'cuz I'd have to google for that.
Your answer
![](https://koobas.hobune.stream/wayback/20220612035705im_/https://answers.unity.com/themes/thub/images/avi.jpg)