I’ve a script on a object that is controlled with sliders. Ive got a maxspeed control slider that controls the speed but when I change the speed down the object responds directly and goes to that speed that is given.
But I want a nice deceleration instead of a direct reaction.
Is it possible to make a Maxspeed, that if it changes during gameplay via a slider, it changes the value of the AddForce to 0 until its given speed is reached and then setting the Maxspeed to the NewMaxspeed.
Or are there other solutions?
Please explain them because I learn best that way. Also use examples so I can train my skill.
Thanks for reading this and it would be great to get help.
First, get the rigidbody’s velocity (Unity - Scripting API: Rigidbody.velocity).
Check to see if the sqrMagnitude of that velocity is greater than your max speed (Unity - Scripting API: Vector3.sqrMagnitude),
If the velocity is too high then you have some options to slow it down.
Option 1 - increase the drag until the velocity is below your set mark. This will act like the brakes on a car. Add more and more drag to stop faster.
Option 2 - Get the inverse of the vector using gameObject.transform.InverseTransformDirection(velocity) (Unity - Scripting API: Transform.InverseTransformDirection). Then use that inverted velocity vector to add force to your object until it is slowed.
Option 3 - Calculate the velocity using Vector3.Lerp (Unity - Scripting API: Vector3.Lerp). This one’s a bit more complicated since you’ll need to take the current velocity, normalize it, and then multiply it by the desired magnitude velocity. That’s the endpoint of the lerp. This will, however give you control over the amount of time the deceleration takes place.
Another option would be to try to stop at a certain position. This one’s a bit complicated and would require lerping the position over the proper deceleration time. I’m not sure if you can do this and make it look very realistic, so I’d say use one of the other methods and if you really need to stop at a specific point it might be better to not use Unity’s physics engine
As for providing you with examples, they’re mostly in the manual. You just need to write the code based on the above principles and learn. Unity’s manual has a lot of great info and you might find the Vector Cookbook section of some use (Unity - Manual: Important Classes - Vectors).