Search code examples
c#unity-game-enginecamera

Need help clamping camera rotation


I am really new to coding and made this code to rotate my camera around the player object but I do not know how I would proceed to clamp the rotation on the X axis.

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

public class FollowPlayer : MonoBehaviour
{
    public float speed;
    public Transform target;

    // Start is called before the first frame update
    void Start()
    {
        
    }
    // Update is called once per frame
    void Update()
    {
        transform.RotateAround(target.position, transform.right, -Input.GetAxis("Mouse Y") * speed);
        transform.RotateAround(target.position, Vector3.up, -Input.GetAxis("Mouse X") * speed);
    }
}

This is my code to rotate the camera, I want to clamp the Mouse Y one.


Solution

  • The trick here is to keep track of the accumulated input and clamping that before doing the transformations. This is easier and less error-prone than trying to decompose the camera's rotation into the correct axes.

    public class FollowPlayer : MonoBehaviour
    {
        public float speed;
        public Transform target;
    
        float vertical;
        float horizontal;
        Quaternion initalRotation;
        Vector3 initialOffset;
    
        // Start is called before the first frame update
        void Start()
        {
            initialRotation = transform.rotation;
            initialOffset = transform.position - target.position;
        }
        // Update is called once per frame
        void Update()
        {
            horizontal += - Input.GetAxis("Mouse X") * speed;
            vertical += - Input.GetAxis("Mouse Y") * speed;
            vertical = Mathf.Clamp(vertical, -20f, 20f);
    
            //always rotate from same origin
            transform.rotation = initialRotation;
            transform.position = target.position + initialOffset;
            transform.RotateAround(target.position, transform.right, vertical);
            transform.RotateAround(target.position, Vector3.up, horizontal);
        }
    }