- Home /
How to Limit Speed of a Rigidbody?
Hey everybody,
Can somebody help out with this bit of code? I'm not sure why it doesn't work.
I am trying to limit the speed of the rigidbody to 10.
// Trying to Limit Speed
if(rigidbody.velocity.magnitude > 10){
rigidbody.velocity = Vector3.ClampMagnitude(rigidbody.velocity, maxSpeed);
print("Why Doesn't this Work?");
}
Why Doesn't this Work? is showing up in the Console, but my speed is not being limited.
Any help is really appreciated.
Thanks!
Is it in Update? Is maxSpeed super big? (and why do you have 10 in the IF, but maxSpeed down below?) $$anonymous$$aybe it does work -- does the ball ever go faster than 10 meters/sec? (if the world is a 2x2 box, a fast-looking ball might be speed 5.) Is some other code increasing the speed again?
It's in FixedUpdate.
Does it matter if 10 or maxSpeed is in the IF? I'm testing different numbers to see if I can get the code to work.
Yes, the Player continues to accelerate.
Have you tried my scipt? I tested on a cube, but it should work for any object
Answer by Radivarig · Apr 08, 2014 at 11:36 PM
Drag this on the cube:
using UnityEngine;
using System.Collections;
[RequireComponent (typeof (Rigidbody))]
public class NewBehaviourScript : MonoBehaviour {
public float maxSpeed = 10f;
void Update()
{
// Trying to Limit Speed
if(rigidbody.velocity.magnitude > maxSpeed){
rigidbody.velocity = Vector3.ClampMagnitude(rigidbody.velocity, maxSpeed);
}
}
void OnGUI()
{
GUI.Label(new Rect(20, 20, 200, 200), "rigidbody velocity: " + rigidbody.velocity);
}
}
Did you figure out what the original problem was? Seems like that might help you later.
This is 3 changes to the code you started with -- FixedUpdate to Update, replace 10 in the IF, delete/reinstall. So one of them was probably the fix.
Answer by xpxilom · Jul 30, 2021 at 03:33 AM
diff.Normalize();
rb2d.AddForce(diff * Aceleracion * Time.fixedDeltaTime);
float speed = Vector3.Magnitude(rb2d.velocity); // test current object speed
if (speed > VelocidadMaxima)
{
float brakeSpeed = speed - VelocidadMaxima; // calculate the speed decrease
Vector3 normalisedVelocity = rb2d.velocity.normalized;
Vector3 brakeVelocity = normalisedVelocity * brakeSpeed; // make the brake Vector3 value
rb2d.AddForce(-brakeVelocity); // apply opposing brake force
}