Orbit Camera

mail@pastecode.io avatar
unknown
csharp
3 years ago
1.4 kB
5
Indexable
Never
using UnityEngine;

public class OrbitCamera : MonoBehaviour
{
    public Transform target;
    public float sensibility = 1.0f;
    public float distance = 5.0f;

    private float pitch;
    private float yaw;
    private Vector2 lastMousePosition;

    void LateUpdate()
    {
        //Get the mouse input (Using "Mouse X/Y" work fine too ofc)
        Vector2 mouseDelta = (Vector2)Input.mousePosition - lastMousePosition;
        lastMousePosition = Input.mousePosition;

        //In this example I move the camera only when the left button is pressed
        if (Input.GetMouseButton(0))
        {
            pitch -= mouseDelta.y * sensibility * 0.01f;                    //Divided by 100 only to get convenient values. (Not the cleanest part of the code)
            pitch = Mathf.Clamp(pitch, -Mathf.PI * 0.1f, Mathf.PI * 0.49f); //Prevents the camera from going too low or too high.
            yaw -= mouseDelta.x * sensibility * 0.01f;
        }

        //Create an offset vector based on pitch and yaw
        float cosPitch = Mathf.Cos(pitch);
        Vector3 offset = new Vector3(Mathf.Cos(yaw) * cosPitch, Mathf.Sin(pitch), Mathf.Sin(yaw) * cosPitch);


        //Set the camera position
        transform.position = target.position + offset * distance;

        //Set the camera rotation
        transform.LookAt(target.position, target.up);
    }
}