# Applying a counter force to cancel out velocity?

I am pretty certain my math here is correct, but I have some lack of understanding of how the unity physics engine works internally. Essentially I want to cap the velocity’s magnitude at a certain value by applying a counter force in the opposite direction with the magnitude of the excess force. I understand I could use a clamp, but I don’t want to for the sake of an accurate simulation. My code:

``````private void AddClampedForce(Vector3 force) {

float sqrMaxSpeed = maxSpeed * maxSpeed;
if(velocity.sqrMagnitude > sqrMaxSpeed ) {
float forceDifference = Mathf.Sqrt(velocity.sqrMagnitude - sqrMaxSpeed);
Vector3 counterForce = -velocity.normalized * forceDifference;

Debug.Log(velocity.magnitude);
// Usually Gives 14 or so, ocassionally higher if I hold two buttons down and move diagonal.
}
}
``````

I am pretty sure that your math is wrong

``````Mathf.Sqrt(velocity.sqrMagnitude - sqrMaxSpeed);
``````

Kudos for comparing squared magnitudes and saving one or two sqrts, that’s what I always recommend. BUT the line above does NOT equal `(velocity - maxSpeed)`
Start there, see if the results improve