- Home /
How do I limit rigidbody2d velocity?
I'm trying to limit my characters speed but nothing I try works. Here's my current code: #pragma strict
var force : Vector2;
var bike : Transform;
var power : int;
var brake : int;
var maxForward : int;
var trigfunction : Vector3;
function Update () {
trigfunction = bike.TransformDirection(Vector3.right);
force.Set(trigfunction.x,trigfunction.y);
if (GetComponent.<Rigidbody2D>().velocity.magnitude < maxForward)
GetComponent.<Rigidbody2D>().AddForce(force);
if (Input.GetKey(KeyCode.UpArrow))
GetComponent.<Rigidbody2D>().AddForce(force*power);
if (Input.GetKey(KeyCode.DownArrow))
GetComponent.<Rigidbody2D>().AddForce(force*brake*-1);
}
What's wrong?
Answer by RLin · Aug 06, 2015 at 01:28 AM
You can check the velocity with velocity.magnitude. If the velocity is too high, disable the forces on the object until it becomes low enough again.
That's sort of what lines 13 and 14 do (but then the later keyboard don't check this. Not sure why not.)
Answer by Owen-Reynolds · Aug 06, 2015 at 05:19 PM
To manually force it to a speed, multiply "too fast" velocities by whatever fraction you need to reduce it to the maximum. For example:
float curSpeed = vel.magnitude;
if(curspeed>maxSpeed) {
float reduction=maxSpeed/curSpeed;
vel *= reduction;
}
Suppose the max speed is 5, and you're going 6 now. That code would multiply the entire xyz velocity by 5/6ths. Which really does reduce the speed by 5/6ths, to give a speed of 5 in whichever direction. It's a common Vector trick.
It doesn't work very well, the rigidbody2d objects still hit speeds way above my speed limit.