- Home /
How to smoothly slow down a non-Rigidbody object
I was wondering how I would smoothly slow down/decelerate to a stop a non-rigidbody object moving in a particular direction.
If it's not a rigidbody, and is moving. It means that you're moving it, in your code, through some various means.
If you're adding 0.5 every frame, then figure out a way to add only 0.45, then 0.4 ... . If you're using a Lerp(start, stop, pct), and pct is increasing by 0.03 each frame, then figure out how to have that 0.03 drift down (maybe when it gets past 0.95?)
Answer by Jeff-Kesselman · Jun 07, 2014 at 07:05 PM
Another approach is to add in a fixed drag by taking a drag rate an s multiplying it by the elapsed time
float drag=2.0; // drag per sec
public void Update(){
float elapsedDrag = drag * Time.deltaTime;
if (rigid body.velocity.x>0) {
rigidbody.velocity.x = Math.max(rigidbody.velocity.x-elapsedDrag,0);
} else {
rigidbody.velocity.x = Math.minn(rigidbody.velocity.x+elapsedDrag,0);
}
if (rigid body.velocity.y>0) {
rigidbody.velocity.y = Math.max(rigidbody.velocity.y-elapsedDrag,0);
} else {
rigidbody.velocity.y = Math.min(rigidbody.velocity.y+elapsedDrag,0);
}
if (rigid body.velocity.z>0) {
rigidbody.velocity.z = Math.max(rigidbody.velocity.z-elapsedDrag,0);
} else {
rigidbody.velocity.z = Math.min(rigidbody.velocity.z+elapsedDrag,0);
}
}
The max/min is to clip it at 0.
True, okay. Same thing but using your own velocity numbers.
Thanks for the suggestions.
Yes, it's a non-RB. Would you $$anonymous$$d, giving me an example of how to use this with a non-RB? I'm not having great success with describing the equivalent conditions to deter$$anonymous$$e the x, y, and z directions/movement (if .. > 0 , etc.) that it's moving in, in order to apply the correct position change.
Answer by HammockHead · Jun 07, 2014 at 05:10 PM
I'd imagine you would interpolate between the rigidbody's current velocity to an end velocity (in this case a velocity of 0,0,0). Something like this could possibly work :
function slowDown(endVeclocity:Vector3) {
startVelocity = rigidbody.velocity;
rigidbody.velocity = Vector3.Lerp(startVelocity,endVelocity,Time.deltaTime)
}
You could of course add a float to the third parameter of the Lerp function to simulate acceleration. Just a warning, I haven't test this yet but it should at least give you an idea.