마우스 조작. 사실 상 탑뷰 게임에서 굉장히 중요한 요소가 아닌가 생각든다
프로젝트를 진행하다가 필요하게 될 상황이 나올 것 같아서 구현을 해봤다
CameraSystem이라는 오브젝트를 통해 카메라를 조정해준다
TopView 라는 Virtual Machine Camera의 Look At, Follow Target을 이 CameraSystem으로 설정 해주고 CameraSystem.cs를 통해서 카메라를 실질적으로 컨트롤 하는 원리다
Virtual Camera의 Follow offset 등 Transposer와 관련된 설정을 스크립트내에서 컨트롤 하기 위해서는 GetComponent를 사용해서 구하면 안된다
GetCinemachineComponent로 캐싱해줘야한다
이거 때문에 삽질 좀 했다..
private void Awake()
{
transposer = virtualCamera.GetCinemachineComponent<CinemachineTransposer>();
screenYValue = 0.5f;
}
W,A,S,D 키 입력을 통해 카메라가 이동 할 방향을 설정하고
마우스 움직임을 통해 카메라 회전 방향을 설정해준다
private void Update()
{
Vector3 inputDir = inputHandler.GetMove();
mouseDir = inputHandler.GetLook();
inputDir = new Vector3(inputDir.x, 0, inputDir.y);
moveDir = transform.forward * inputDir.z + transform.right * inputDir.x;
rotateDir = 0f;
if (Input.GetMouseButton(1) && mouseDir.x > 0) rotateDir = 1f;
if (Input.GetMouseButton(1) && mouseDir.x < 0) rotateDir = -1f;
}
Late Update에 코드를 작성함
해당 부분을 통해 이동 및 회전을 구현
private void LateUpdate()
{
transform.position += moveDir * moveSpeed * Time.deltaTime;
transform.eulerAngles += new Vector3(0, rotateDir * rotateSpeed * Time.deltaTime);
회전 시에 마우스 포인터가 고정 되도록 설정
if (Input.GetMouseButton(1))
{
inputHandler.CursorLocked = true;
inputHandler.CursorInputForLook = true;
Cursor.visible = false;
}
if (Input.GetMouseButtonUp(1))
{
inputHandler.CursorLocked = false;
inputHandler.CursorInputForLook = false;
Cursor.visible = true;
}
스크롤을 통해 transposer의 FollowOffset 값을 변경 시킬 변수 yAxis, zAxis 업데이트
부드러운 전환을 위해서 Mathf.Lerp 사용
한계치를 설정해줘서 땅을 뚫거나 하는 상황을 방지
if (Input.mouseScrollDelta.y < 0)
{
yAxis += 5;
zAxis -= 5;
}
if (Input.mouseScrollDelta.y > 0 )
{
yAxis -= 5;
zAxis += 5;
}
if (Input.GetMouseButton(1) && mouseDir.y > 0) yAxis -= 20 * Time.deltaTime;
if (Input.GetMouseButton(1) && mouseDir.y < 0) yAxis += 20 * Time.deltaTime;
yAxis = Mathf.Clamp(yAxis, 5, maxMinLimit);
zAxis = Mathf.Clamp(zAxis, -maxMinLimit, -5);
transposer.m_FollowOffset.y = Mathf.Lerp(transposer.m_FollowOffset.y, yAxis, Time.deltaTime * zoomSpeed);
transposer.m_FollowOffset.z = Mathf.Lerp(transposer.m_FollowOffset.z, zAxis, Time.deltaTime * zoomSpeed);