How do I set maximum velocity to a RigidBody2D ?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Skyfrit
:warning: Old Version Published before Godot 3 was released.

I want to set the maximum velocity to a RigidBody2D, so it can’t exceed the speed limit.

:bust_in_silhouette: Reply From: ericdl
var max_speed = 100

...

if abs(get_linear_velocity().x) > max_speed or abs(get_linear_velocity().y) > max_speed:
	var new_speed = get_linear_velocity().normalized()
	new_speed *= max_speed
	set_linear_velocity(new_speed)

Thanks for the answers.

Skyfrit | 2016-09-16 04:39

I assume this would be used in integrate_forces().

If that’s the case, I would also assume regardless of what you set linear velocity to, external forces such as gravity or other physics bodies will affect it after integrate forces. If so, the clamp only affects a body’s speed before external forces are added to it. The actual total in-game velocity would look like this:

	totalLinearVelocity = clampedLinearVelocity + VelocityFromExternalForces

This presents a problem if you want to clamp the total velocity.

Is there a way to tell the rigidbody to not exceed a certain velocity when affected by external forces?

PitaBread | 2021-06-16 04:11