x


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?

more ▼

asked Jul 30 '10 at 07:23 PM

Flipbee9 gravatar image

Flipbee9
73 19 20 25

(comments are locked)
10|3000 characters needed characters left

4 answers: sort voted first

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;
    }
}
more ▼

answered Jul 30 '10 at 07:39 PM

Mike 3 gravatar image

Mike 3
30.7k 10 67 255

You could check for IsAsleep() as well, also if .rigidbody is null, but that's just being nitpicky :P

Jul 30 '10 at 07:49 PM qJake

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

Jul 30 '10 at 08:03 PM Mike 3
(comments are locked)
10|3000 characters needed characters left

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)

more ▼

answered Jul 30 '10 at 10:29 PM

boribhi gravatar image

boribhi
152 6 6 19

(comments are locked)
10|3000 characters needed characters left

maybe you could increase the drag property on inclined downward slopes.. it is not the best solution but it worked for me.

more ▼

answered Jul 31 '10 at 09:27 AM

Neo 2 gravatar image

Neo 2
28 1 1 5

(comments are locked)
10|3000 characters needed characters left
more ▼

answered Oct 05 '10 at 10:58 PM

Ehren gravatar image

Ehren
4.2k 35 43 77

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x1864
x330
x137

asked: Jul 30 '10 at 07:23 PM

Seen: 3944 times

Last Updated: Jul 30 '10 at 07:23 PM