Godot C# node rotation clamping

Godot Version

4.2.1 .NET

Question

How do you clamp one axis of rotation on a Node3D?
I Tried, but it’s not restricting the movement on the x axis at all. Here’s My Code:

I was about to debug your issue when I found your problem:

Rotation returns the rotations in radians, which is not what you are expecting in your code - you are clamping by 90 degrees.
To fix your issue, you should either use RotationDegrees or alter your clamp to the following:

Using a correct clamping range:

public override void _Process(double delta) {
    float halfPi = Mathf.Pi / 2f;  // This is 90 degress in radians
    float x = Mathf.Clamp(camera.Rotation.X, -halfPi, halfPi);
    float y = camera.Rotation.Y;
    float z = camera.Rotation.Z;
    camera.Rotation = new Vector3(x, y, z)
}

Using RotationDegrees:

public override void _Process(double delta) {
    float x = Mathf.Clamp(camera.RotationDegrees.X, -90f, 90f);
    float y = camera.RotationDegrees.Y;
    float z = camera.RotationDegrees.Z;
    camera.RotationDegrees = new Vector3(x, y, z)
}

Helper methods for converting between radians and degrees also exist: Mathf.DegToRad, Mathf.RadToDeg.

2 Likes

Ah okay… It works now. Thanks!

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.