unity/유니티 초보

Unity - 부드러운 카메라 회전

rimugiri 2024. 5. 27. 04:53
728x90
using UnityEngine;

public class CameraTest : MonoBehaviour
{
    [SerializeField] Transform target;
    [SerializeField] float mouseXSpeed = 10f;
    [SerializeField] float mouseYSpeed = 10f;

    //카메라 pivot값
    [SerializeField] Vector3 cameraPivot = new Vector3(0.2f, 1.5f, -2f);

    // 마우스 회전값
    float xRotation = 0f;
    float yRotation = 0f;

    // 마우스 회전 제한값
    [SerializeField] float minXRotation = -45f;
    [SerializeField] float maxXRotation = 45f;
    [SerializeField] float minYRotation = -30f;
    [SerializeField] float maxYRotation = 45f;

    // 부드러운 회전을 위한 변수
    [SerializeField] float smoothTime = 0.1f;
    float xRotationVelocity = 0f;
    float yRotationVelocity = 0f;

    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        transform.position = cameraPivot;
    }

    void Update()
    {
        MouseLookAt();
    }

    private void ResetMouseRotation()
    {
        xRotation = 0f;
        yRotation = 0f;
    }

    private void MouseLookAt()
    {
        float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * mouseXSpeed;
        float mouseY = Input.GetAxisRaw("Mouse Y") * Time.deltaTime * mouseYSpeed;

        xRotation -= mouseY;
        yRotation += mouseX;

        xRotation = Mathf.Clamp(xRotation, minXRotation, maxXRotation);
        yRotation = Mathf.Clamp(yRotation, minYRotation, maxYRotation);

        float smoothX = Mathf.SmoothDampAngle(transform.eulerAngles.x, xRotation, ref xRotationVelocity, smoothTime);
        float smoothY = Mathf.SmoothDampAngle(transform.eulerAngles.y, yRotation, ref yRotationVelocity, smoothTime);

        Vector3 dir = new Vector3(smoothX, smoothY, 0);

        transform.rotation = Quaternion.Euler(dir);
    }
}
728x90