Set a maximum rotation angle for a Rigidbody2D

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

I’m trying to implement something akin to a seesaw scale in 2D (that is, there’s a horizontal bar, and two objects connected to it, one on the right and one on the left. When one becomes heavier than the other, it goes down, and the other object goes up).Example of a seesaw scale

I implemented it like this (first image in the collection):
Relevant image and videos


[In the videos, I set the weight to the left to 1 kg, and the one on the right to 2 kg]
As you can see from the first video in the collection (“No code”), by default, the horizontal bar that connects the two Rigidbodies swings a lot when one body is heavier than the other. I wanted to limit the rotation of the bar so that it never went further than 45° (or -45°). I tried the following two things, but they didn’t quite solve my problem:

  1. Changing angular_velocity.

I tried adding the following script to the center bar.

extends RigidBody2D

func _integrate_forces(state):
	if (rotation_degrees > 45
	or rotation_degrees < -45):
		angular_velocity = 0;

The result can be seen in the second video (“Changing angular velocity”). As you can see, the center bar is indeed slowed down and doesn’t swing, but it still goes beyond 45° to almost 90°.

  1. Changing rotation_degrees.

Then I tried fixing the center bar’s rotation degrees to 45° whenever they were higher than 45° (or to -45° when they were lower than -45°).

extends RigidBody2D

func _integrate_forces(state):
	if rotation_degrees > 45:
		rotation_degrees = 45;
	elif rotation_degrees < -45:
		rotation_degrees = -45;

The result is in the third video (“Changing rotation_degrees”). This time the bar does stop instantly, but evidently the two Rigidbodies attached to it keep on swinging.

Is there a way to get the center bar to stop at 45°, and stop its Rigidbodies with it?