How to limit rotation on a RigidBody2D?

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

Currently I am making a clone of the game Flappy Bird for practice. I am representing the bird as a RigidBody2D.

extends RigidBody2D

func _ready():
    pass

func _input(event):
    if Input.is_action_just_pressed("input_action_flap"):
        bird_flap()

func _physics_process(delta):
    print(self.rotation_degrees)
    
    self.rotation_degrees = -45
    
    print(self.rotation_degrees)
    
func bird_flap():
    var des_linear_velocity_x : float = get_linear_velocity().x
    var des_linear_velocity_y : float = -750
    var des_angular_velocity  : float = -3
    
    set_linear_velocity(Vector2(des_linear_velocity_x, des_linear_velocity_y))
    set_angular_velocity(des_angular_velocity)

I am playing around with ways to limit the possible rotation of the Node. However, I am running into some issues.

-135.234329
-45
-137.498474
-45
-139.724884
-45
+171.914169
-45
+164.066986
-45

The values of the rotation seem to be flickering wildly due to Godot’s built-in physics engine. And when I try to use the method clamp(…) - I subsequently experience wild flickering of my character sprite’s rotation.

self.rotation = clamp(self.rotation, deg2rad(-45), deg2rad(+45))

Does anyone know how to fix this?

I would not rotate the RigidBody2D in your case, but rotate the srpite instead. changin manually rotation of a RigidBody can be unpredicrable, as the rotation is handled by the engine.

In your case, i would use RigidBody2D in character mode to avoid rotation at all, and rotate the sprite of the bird instead. You should be able to manually change and clamp that rotation.

p7f | 2020-08-18 13:45

:bust_in_silhouette: Reply From: klaas

Hi,
you better restrict the rotation and the angular momentum in the _integrated_forces() function. When you set the rotation you should reset the angular momentum.

Havent tested but pretty sure this would work.

Do you happen to know how often _integrate_forces(...) is called?

I had initially opted to use _physics_process(...) because of familiarity - in that I knew that it would be reliably called after a fixed interval had passed.

AlanGODOT | 2020-08-18 20:04