Constraint an object speed

Hello,

I don’t want my ball goes at a greater speed as I set in “AddForce()”.

Is this code correct ?

    void Update()
    {
        if (ball.GetComponent<Rigidbody>().velocity.magnitude > 250.0f)
        {
            ball.GetComponent<Rigidbody>().SetMaxAngularVelocity(250.0f);
        }
    }

You’re muddling up velocity (position) with angularVelocity (rotation). Also you don’t need to keep setting a maximum value every frame - you can just set it once and it will persist. You should also try to avoid using GetComponent in Update - it’s expensive. Find the rigidbody once in Start and re-use the result from them on.

Try this instead:

private Rigidbody rb;

void Start() {
  rb = ball.GetComponent<Rigidbody>();
}

void Update()
 {
     if (rb.velocity.magnitude > 250.0f)
     {
         rb.velocity = rb.velocity.normalized * 250f;
     }
 }

SetMaxAngularVelocity only constraints the rotational velocity. I assume you want to constraint the translational velocity since you state this in your if-condition?
And: Put in in the FixedUpdate() loop!

To constrain the translational velocity you got two options:

  1. The non-physics way (I don’t recommend because you gonna mess with the physics engine)
  2. The physics way which probably takes a little more time to get exactly what you want

For (1) You could write something like this:

  const float maxSpeed=250;  
  void Start()
    {
    rigidbody=GetComponent<Rigidbody>();
    }
    void FixedUpdate()
    {
                 if(rigidbody.velocity.magnitude > maxSpeed)
                 {
                        rigidbody.velocity = rigidbody.velocity.normalized * maxSpeed;
                 }
    }

For (2) you can either experiment with the drag value of your rigidbody in the inspector or write your own function, something like this:

rigidbody.AddForce(-rigidbody.velocity*dampC); //dampfC is a damping Coefficient you can define yourself