How to limit a movement vector without affecting gravity

Hello, I wrote a script to control my spaceship, and I can limit its speed by using Vector3.ClampMagnitude(myRigidbody.velocity). However it affects a gravity and if I move down to the planet’s surface my max speed is limited and it is not realistic. My question is how limit my movement vector( I use AddForce to apply it to my rigidbody) but keep gravity vector, which I also apply to rigidbody by using AddForce method, unlimited.

If your gravity is not “world space” down and you only want to clamp the tangent velocity you can seperate the velocity into the “vertical” / gravity part and the “horizontal” / tangential part.

Of course to do this you have to provide the direction of gravity as a vector for reference.

``````public Vector3 ClampVelocity(Vector3 aVelocity, Vector3 aGravity, float aMaxTangentialVelocity)
{
var grav = Vector3.Project(aVelocity, aGravity);
var tan = aVelocity - grav;
tan = Vector3.ClampMagnitude(tan, aMaxTangentialVelocity);
return tan + grav;
}
``````

This method basically works the same as “ClampMagnitude” but it removes the velocity part along the gravity direction, clamps the remaining part and adds the gravity part back at the end.

You could try limiting the velocity only in non-downward directions.

try this (untested)

`````` Rigidibody rb;
bool separatedDownardVector = false;
Vector3 tempVelocity = rb.velocity;
// removes the y component if the object is moving downward
if (tempVelocity.y < 0f) {
separatedDownardVector = true;
tempVelocity.y = 0f;
}
// clamp the magnitude of the edited velocity.
tempVelocity = tempVelocity.normalized * Mathf.Clamp(0f, maximumSpeed, tempVelocity.magnitude);
// adds the downard vector back, if it was removed earlier.
if (separatedDownardVector) tempVelocity += rb.velocity.y;
rb.velocity = tempVelocity;
``````