• Tutorials
  • how to clamp the rotation of the camera in c#

here is the code
public override void _UnhandledInput(InputEvent @event)
{
if (@event is InputEventMouseMotion)
{
Vector3 cam_rot = cam.Rotation.Clamp(new Vector3(-90, 0, 0), new Vector3(90, 0, 0));
InputEventMouseMotion eventa = @event as InputEventMouseMotion;
RotateY(-(eventa.Relative.X * 0.01f));
cam.RotateX(eventa.Relative.Y * 0.01f);
}
}

i need to find a way to clamp the rotation of the camera , ive used Math.clamp , didnt work , i have even used the clamp method inside the Rotation

    averageCOMRE None of the Vector3 methods do stuff in-place, Clamp() included. They always return a new value that you need to re-assign to the actual object the method was called on, if you want them to act as if they work in-place.

    foo = foo.Clamp(...)

    averageCOMRE

    public override void _UnhandledInput(InputEvent @event)
    {
         if (@event is InputEventMouseMotion)
         {
              Vector3 cam_rot = cam.Rotation.Clamp(new Vector3(-90, 0, 0), new Vector3(90, 0, 0));
              InputEventMouseMotion eventa = @event as InputEventMouseMotion;
              RotateY(-(eventa.Relative.X * 0.01f));
              cam.RotateX(eventa.Relative.Y * 0.01f);
         }
    }

    you are doing it in the wrong order. first rotate the camera, THEN clamp it.

    @export var cam_clamp : Vector2 = Vector2(deg_to_rad(-45), deg_to_rad(45))
    
    func _input(event):
    	if cursor_mode:
    		if event is InputEventMouseMotion:
    			mouselook = event.relative
    			rotate_y(mouselook.x * sensitivity.x)
    			cam_y.rotate_x(mouselook.y * sensitivity.y)
    
    func _physics_process(_delta):
    	cam_y.rotation.x = clampf(cam_y.rotation.x, cam_clamp.x, cam_clamp.y)

    edit: though in C# you have to put the camera rotation into a variable first and then assign it (C# sucks)

    
    Vector3 cam_y_rot = cam_y.Rotation;
    cam_y_rot.X = Mathf.Clamp(cam_y.Rotation.X, cam_clamp.X, cam_clamp.Y);
    cam_y.Rotation = cam_y_rot;