아래 코드가 짜여진 방식은 시네머신 카메라를 활용할 때 특히, 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;을 사용해 프레임 단위로 실행되기 때문에, 메인 스레드를 블록하지 않고 자연스러운 애니메이션을 구현할 수 있다.간결 & 직관적 코드