TransWikia.com

Mathf.Clamp not Working Properly

Game Development Asked by Shubhendra Chaddha on February 3, 2021

I want to clamp the vertical rotation of the first person controller I was making. I want to restrict the vertical rotation of the main camera between -90 and 90 degrees. The code is as follows:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MouseY : MonoBehaviour
{
    [SerializeField]
    private float _sensitivity = 5.0f;
    private float _verticalInput;

    // Update is called once per frame
    void Update()
    {
        _verticalInput = Input.GetAxis("Mouse Y") * _sensitivity;
        Vector3 lookDirectionY = transform.localEulerAngles;
        lookDirectionY.x -= _verticalInput;
        lookDirectionY.x = Mathf.Clamp(lookDirectionY.x, -90f, 90f);
        transform.localEulerAngles = lookDirectionY;
    }
}

In the above code, Mathf.Clamp does not work for -90. On reaching 0 degrees, it reels back to the +90 degrees. What could be the reason for this and how to resolve it?

One Answer

This example shows how you can convert any angle into the range -180 to 180.

Vector3 lookDirection = transform.localEulerAngles;
float x = lookDirection.x;
x -= _verticalInput;
//convert `x` into the range -180 to 180
x = x % 360;
if (x > 180) x -= 360;
else if (x < -180) x += 360;
//clamp and apply
x = Mathf.Clamp(x, -90f, 90f);
lookDirection.x = x;
transform.localEulerAngles = lookDirection;

Answered by Kevin on February 3, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP