- Home /
Limit Rigidbody Velocity
So, I'm making a game which the player controls a ball down a hill. I made it so it adds a bit of speed every few frames but what I want is when the player reaches a certain velocity their speed will be limited. How would I do this?
Answer by Mike 3 · Jul 30, 2010 at 07:39 PM
Something along these lines should do it
var maxVelocity : float = 10.0; //set in the inspector
function Update() { var velocity = rigidbody.velocity; if (velocity == Vector3.zero) return;
var magnitude = velocity.magnitude;
if (magnitude > maxVelocity)
{
velocity *= (maxVelocity / magnitude);
rigidbody.velocity = velocity;
}
}
You could check for IsAsleep() as well, also if .rigidbody is null, but that's just being nitpicky :P
Indeed to the rigidbody is null check, but I wouldn't check for IsAsleep() - it'll hit zero velocity first, and asplode the calculations o.O
Answer by boribhi · Jul 30, 2010 at 10:29 PM
For rigidbpdy, I use FixedUpdate http://unity3d.com/support/documentation/ScriptReference/MonoBehaviour.FixedUpdate.html
var velocityMax : float; //say 10 @ the inspector
var speedRate: float; //say 2 @ the inspector
function FixedUpdate()
{
var vMotion = Input.GetAxis ("Vertical") * speedRate;
var velocity = rigidbody.velocity;
var vMagnitude = velocity.magnitude;
if(vMagnitude < velocityMax)
{
rigidbody.velocity += vMotion;
}
}
In this case, more velocity will be added only if the velocity is less than the limit (velocityMax)
Answer by Neo 2 · Jul 31, 2010 at 09:27 AM
maybe you could increase the drag property on inclined downward slopes.. it is not the best solution but it worked for me.
Answer by Ehren · Oct 05, 2010 at 10:58 PM
See this question: http://answers.unity3d.com/questions/2502/limiting-rigidbody-velocity