쯔꾸르식 유니티 게임 공부

04.카메라 플레이어 추적

ruripanda 2024. 12. 30. 12:32

본 강좌는 케이디님의 쯔꾸르풍 유니티 게임 만들기 강좌를 참고하여 만들었음을 알려드립니다

using UnityEngine;

public class CamerManager : MonoBehaviour
{
    public GameObject target;//카메라가 따라갈 대상
    public float moveSpeed;//카메라가 얼마나 빠른 속도로 대상을 추적할지
    private Vector3 targetPosition;//대상의 현재 위치 값

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (target.gameObject != null)
        {
            targetPosition.Set(target.transform.position.x, target.transform.position.y, this.transform.position.z);

            this.transform.position = Vector3.Lerp(this.transform.position, targetPosition, moveSpeed * Time.deltaTime);
            //Time.deltaTime 초당 이동구현용 코드
        }
    }
}

 

1.카메라가 따라갈 대상을 지정한다

 

플레이어 캐릭터를 Target에 넣는다

 

그리고 카메라의 이동속도를 설정한다

 

여기서 꿀팁!

위의 targetPosition은 타깃의 x위치, 타깃의 y위치, this.transfrom.position을 해놨는데

this는 자신의 트랜스프롬 포지션을 가지고 온 것이다

 

이렇게 된 이유는

 

추적하는 카메라는 더 높은 위치에서 바라보도록 세팅되어 있기 때문에 z축마저 캐릭터와 같으면 안되기 때문!

 

다음은 카메라가 이동하는 코드를 적어넣는다

Vector3.Lerp(this.transform.position, targetPosition, moveSpeed * Time.deltaTime로 적어놓는대 뜻은

 

Lerp의 뜻은 A값과 B값 사이의 선형보간으로 중간값을 반영한다

예를 들어서

(1,19,0.5f) =5

(5,10,0.5f)=7.5

쉽게 말해서 중간 값을 반영한다고 생각을 한다

 

this.transform.position은 자신의 포지션

targetPosition 추적하는 플레이어 포지션

moveSpeed는 카메라의 이동속도

Time.deltaTime는 초당행동으로 값을 수정해준다