How to lock a RigidBody2D to a certain axis?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Excel

I am creating a game where a specific part of it requires you to combine gears together to complete the level. They are implemented using RigidBody2D and I need them to be locked to a axis while still having physics applied to them. Any way to do this?

:bust_in_silhouette: Reply From: sparkart

Try using

 set_axis_lock

Here is some more information about it:

This doesn’t work for RigidBody2D, though.

Thomas Karcher | 2019-06-12 08:57

:bust_in_silhouette: Reply From: Thomas Karcher

You can alter the physics behaviour with the _integrate_forces function. In your case, you could take the calculated velocity and remove the x part of it:

func _integrate_forces(state):
    var vel = state.get_linear_velocity ()
    state.set_linear_velocity (Vector2 (0, vel.y))