Cinemachine CameraControler

John Jean·2025년 2월 2일

Unity

목록 보기
13/19

아래 코드가 짜여진 방식은 시네머신 카메라를 활용할 때 특히, fov를 변경해 줌인, 아웃 할때 자주 사용되는 방식이라고 한다.

public class CameraControler : MonoBehaviour
{
    [SerializeField] float minFOV = 20f;
    [SerializeField] float maxFOV = 120f;
    [SerializeField] float zoomDuration = 1f;
    [SerializeField] float zoomSpeedModifier = 5f;

    CinemachineCamera cinemachineCamera;

    private void Awake()
    {
        cinemachineCamera = GetComponent<CinemachineCamera>();
    }
    public void ChangeCameraFOV(float speedAmount)
    {
        StopAllCoroutines(); // Unity Built in method which stops all coroutines to make sure coroutines activate only once at a time.
        StartCoroutine(ChangeFOVRoutine(speedAmount));
    }

    IEnumerator ChangeFOVRoutine(float speedAmount)
    {
        float startFOV = cinemachineCamera.Lens.FieldOfView;
        float targetFOV = Mathf.Clamp(startFOV + speedAmount * zoomSpeedModifier, minFOV, maxFOV);

        float elapsedTime = 0f;

        while (elapsedTime < zoomDuration)
        {
            float t = elapsedTime/zoomDuration;
            elapsedTime += Time.deltaTime;

            cinemachineCamera.Lens.FieldOfView = Mathf.Lerp(startFOV, targetFOV, t);
            yield return null;
        }

        cinemachineCamera.Lens.FieldOfView = targetFOV;
    }
}
  • while (elapsedTime < zoomDuration) 루프를 통해 매 프레임마다 현재 시간에 비례하여 FOV를 Mathf.Lerp를 사용해 선형 보간(Lerp) 방식으로 변화시킨다.

코루틴을 사용한 이유?

  • 순차적 코드 흐름
    별도의 상태 변수나 조건문을 사용하지 않아도 구현 가능하다.
  • 자체 멈춤기능 (StopAllCoroutines();)
    실행 및 중지하기 편하다.
  • 비동기 실행
    코루틴은 yield return null;을 사용해 프레임 단위로 실행되기 때문에, 메인 스레드를 블록하지 않고 자연스러운 애니메이션을 구현할 수 있다.
    이로 인해 다른 게임 로직이나 렌더링 작업에 영향을 주지 않으면서 동작함.
  • 간결 & 직관적 코드
    따로 타이머나 상태관리를 할 필요없이, 단순한 반복문과 yield 키워드로 시간 기반의 작업을 구현할 수 있어 코드가 훨씬 간결해진다.
profile
크래프톤 6기 정글러

0개의 댓글