Search code examples
c#unity-game-enginequaternions

Problem with Mathf.Clamp and rotation in Unity


I have a problem with my camera movement. I want to limit my camera rotation, but I don't know how to do this. I searched for a solution, but I was not able to find one.

In my current code, my camera rotates rapidly in any direction and I don't know how to implement the Mathf.Clamp correctly.

Here is my code:

public float rightSpeed = 20.0f;
public float leftSpeed = -20.0f;
public float rotationLimit = 0.0f;

void Update()
{
    //EdgeScrolling
    float edgeSize = 40f;
    if (Input.mousePosition.x > Screen.width - edgeSize)
    {
        //EdgeRight
        transform.RotateAround(this.transform.position, Vector3.up, rotationLimit += rightSpeed * Time.deltaTime);
    }

    if (Input.mousePosition.x < edgeSize)
    {
        //EdgeLeft
        transform.RotateAround(this.transform.position, Vector3.up, rotationLimit -= leftSpeed * Time.deltaTime);
    }

    rotationLimit = Mathf.Clamp(rotationLimit, 50f, 130f);
}

Solution

  • RotateAround method rotates by an angle. It doesn't assign the angle value you pass it. In this case I would suggest using a different approach. Instead of RotateAround method use the eulerAngles property and assign the rotation values directly.

    Example

    using UnityEngine;
    
    public class TestScript : MonoBehaviour
    {
        public float rightSpeed = 20.0f;
        public float leftSpeed = -20.0f;
    
        private void Update()
        {
            float edgeSize = 40f;
            
            if (Input.mousePosition.x > Screen.width - edgeSize)
                RotateByY(rightSpeed * Time.deltaTime);
            else if (Input.mousePosition.x < edgeSize)
                RotateByY(leftSpeed * Time.deltaTime);
        }
    
        public void RotateByY(float angle)
        {
            float newAngle = transform.eulerAngles.y + angle;
    
            transform.eulerAngles = new Vector3(
                transform.eulerAngles.x,
                Mathf.Clamp(newAngle, 50f, 130f),
                transform.eulerAngles.z);
        }
    }