Limiting Velocity Speed

I’m attempting to limit the velocity speed of a rigidbody.

inside void FixedUpdate()…

float fVelocitySqrMagnitude = m_oThisRigidbody.velocity.sqrMagnitude;
			
if (fVelocitySqrMagnitude > m_fMaxSpeed * m_fMaxSpeed)
{
	m_oThisRigidbody.velocity = m_oThisRigidbody.velocity.normalized * m_fMaxSpeed;
}

Though this doesn’t seem to be doing the trick.

I believe forces are applied to the rigidbody post-fixedupdate meaning even when I limit the velocity it is immediately being exceeded and the rigidbody moves further than desired.

Any ideas?

Why not use a simple code.
In this case the speed is always the same, there unless the number rise.

#pragma strict

var curSpeed : float = 1;


function FixedUpdate () {
	
	if (Input.GetKey(KeyCode.W))
	{
		this.rigidbody.velocity = Vector3(0,0, curSpeed);
		Debug.Log("Speed "+ curSpeed );		
	}	
}

I have no answers. Just shooting into the darkness…

Maybe try putting it in OnCollisionExit? What is applying forces to your rigidbody? Maybe you have to clamp the velocity every time you apply a force?

Use clampMagnitude:
Description
Returns a copy of vector with its magnitude clamped to maxLength.

edit: just to be clear, use it to clamp rigidbody.velocity vector

Force is applied automatically by gravity, collision and joints in some cases. I guess I can clamp the velocity post collision but there is still the issue with everything else. I’m not actually applying forces directly.

That basically does exactly what my code does. The issue, I believe, is to do with velocity being calculated post FixedUpdate()… not with how I’m setting the velocity.

Okay… i see. How about:

if (rb.velocity > maxVel) rb.addForce(oppositeDirection *rb.velocity.magnitude);

Idea is add counter force …i think it should also work with gravity etc