How do I rotate a 3D RigidBody around a global axis?

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

My current code is at the bottom, but here’s a description of what I’m trying to accomplish:

I have a 3D RigidBody. When I yaw, I want to rotate it back and forth around the global Y axis. If it’s not rotated at all, my current code works. Take a look at this gif: Imgur: The magic of the Internet

First, I yaw left and right. Then, I pitch up and down. It works correctly. Then, I yaw left, and pitch up, and it flips wildly end over end.

The behavior I want is this (demonstrated in editor): Imgur: The magic of the Internet

extends RigidBody

var yaw_force = 5
var pitch_force = 5

func _ready():

func _integrate_forces(state):	
	var yaw_axis = Vector3(0,1,0)
	var pitch_axis = Vector3(0,0,1)
	if Input.is_action_just_pressed("game_yaw_left"):
		state.apply_torque_impulse(yaw_force * yaw_axis)

	if Input.is_action_just_pressed("game_yaw_right"):
		state.apply_torque_impulse(-yaw_force * yaw_axis)

	if Input.is_action_just_pressed("game_pitch_up"):
		state.apply_torque_impulse(pitch_force * pitch_axis)

	if Input.is_action_just_pressed("game_pitch_down"):
		state.apply_torque_impulse(-pitch_force * pitch_axis)