Search code examples
unity-game-enginegame-physicsrigid-bodies

Making rigidbody magnitude constant in Unity


I am trying to keep the magnitude of a rigidbody at a constant speed of 3.5. I don't want it lower or higher than that.

Here's what I did so far in FixedUpdate()

        if(rb.velocity.magnitude > 3.5f)
        {
            Debug.Log("ABOVE");
            rb.velocity = Vector2.ClampMagnitude(rb.velocity, 3.5f);
        }
        if(rb.velocity.magnitude < 3.5f)
        {
            Debug.Log("BELOW");
            // Not sure if calculation below is correct
            rb.velocity = rb.velocity.normalized * 3.5f;
        }

I know I implemented the first if statement correctly (clamping if it is over 3.5). I've searched around online and this is what some people suggested when it comes to clamping the magnitude if it exceeds the desired limit.

However, I'm not sure if I implemented the second if statement correctly (if the magnitude is lower than 3.5). I couldn't find any online posts/questions regarding this.

My question is: what is the correct way of setting the rigidbody's velocity if it goes lower than the desired speed? I have tested that clamping only works if the value exceeds the limit.

I want to keep the current direction, by the way. I just want to change/increase the speed. I'm not sure if using normalized is correct.

Appreciate any help. Still a newbie with physics/math programming.


Solution

  • Your calculation is correct.

    You could also do what xyLe_ suggested in a comment and use only that:

    if(rb.velocity.sqrMagnitude != 3.5f*3.5f)
        rb.velocity = rb.velocity.normalized * 3.5f;
    

    Calling a normalization is a bit time consuming (it needs a square root) but you won't notice any problem if you don't run thousands of instances of this object (and I suppose that the ClampMagnitude function needs a square root anyway and wouldn't be more efficient)

    Edit: corrected the code regarding comment from yes