How to I limit x rotation on a 3d node?

Godot 4.3

func _process(delta: float) -> void:
	self.global_rotation.x = clamp(selfrotation, -50/4, 50)
	var look2 := Input.get_axis("uplook", "dowlook")
	if self.global_rotation.x <= 50 and self.global_rotation.x >= -50:
		if look2:
			self.global_rotation.x -= (look2 * lookvert) * delta
	else:
		self.global_rotation.x = self.global_rotation.x
		restrict = false

How do I limit x rotation (Node3d object here)

If the node is PhysicsBody3D, you can set axis_lock_angular_x to true.

1 Like

The code you’re showing is attempting to clamp the x-rotation of your Node3D by using degrees to configure an upper and lower bound for your clamp().
This does not work because the rotation for each axis is stored in radians - not degrees (see Node3D class reference).

Another thing that is wrong with your code is the fact that you clamp your rotation before modifying it. This will result in jittery rotations at the specified bounds whenever the user attempts to move past them. Therefore, clamp the rotation after modifying it.

Solution

  • Specify your x-axis bounds in radians; or use deg_to_rad() to convert your existing values.
  • Clamp the rotation after modifying - not before.

Code example:

func _process(delta: float) -> void:
	# Modify rotation
	var look2 := Input.get_axis("uplook", "dowlook")
	if self.global_rotation.x <= 50 and self.global_rotation.x >= -50:
		if look2:
			self.global_rotation.x -= (look2 * lookvert) * delta
	else:
		self.global_rotation.x = self.global_rotation.x
		restrict = false

	# Clamp modified rotation
	var x_low = deg_to_rad(-50/4)
	var x_high = deg_to_rad(50)
	self.global_rotation.x = clamp(self.global_rotation.x, x_low, x_high)

EDIT: I’m not sure whether your selfrotation is an error or an actual variable. In the example, I’ve substituted it for self.global_rotation.x but if it is a variable you feel that you need to use, don’t forget to insert it back in.