개요

  • 2D에서 사용할만한, SmoothCamera 구현을 기록한다.

코드

using UnityEngine;

// 부드러운 2D 카메라 이동
public class Smooth2DCamera : MonoBehaviour
{
    public Transform target = null;
    public float smoothSpeed = 0.125f;
    public Vector3 offset;

    private void LateUpdate()
    {
        // 카메라의 위치 = target의 위치 + offset
        // offset이 필요한 이유는 target의 중심에 camera가 위치하면 target이 보이지 않기 때문에
        Vector3 desiredPosition = target.position + offset;

        // 원하는 위치 구하기
        // Lerp이라는 선형 보간 함수를 이용하여, smoothSpeed 만큼 이동한 거리를 구한다.
        // smoothSpeed가 0.1인 경우, 10% 이동한 값을 구한다.
        Vector3 smoothedPosition = Vector3.Lerp(
            transform.position, 
            desiredPosition, 
            smoothSpeed);

        // 현재 위치를 업데이트 한다.
        transform.position = smoothedPosition;

        // 카메라는 따라가는 대상을 바라본다.
        transform.LookAt(target);
    }
}

출처

+ Recent posts