Unity/기타

안드로이드에서 드래그를 통한 카메라 줌인, 줌아웃 구현

s0002 2023. 3. 19. 23:43

원하는 기능

캐릭터는 항상 화면 중앙에 있음

터치 두 군데 해서 손가락 간 거리 좁히면 줌아웃, 늘리면 줌인


구현

자료를 찾아보니까 이미 잘 작성해둔 분들이 많아서 그걸 참고하고

우리 게임에 맞게 세부 값만 조절했다

 

Move 함수를 통해 항상 캐릭터를 바라보며 이동하도록,

ZoomInOut 함수를 통해 터치를 통해 줌인 줌아웃이 가능하도록 했다

using UnityEngine;

public class HSYCamera : MonoBehaviour
{
    public Transform target;        // 따라다닐 타겟 오브젝트의 Transform
    public HSYPlayer player;

    private Transform tr;               // 카메라 자신의 Transform

    public float perspectiveZoomSpeed = 0.5f;

    void Start()
    {
        tr = GetComponent<Transform>();
    }

    void Update()
    {
        if (Input.touchCount == 2) //손가락 2개가 눌렸을 때
        {
            this.ZoomInOut();
        }
    }

    void LateUpdate()
    {
        this.Move();   
    }

    private void ZoomInOut()
    {
        Touch touch0 = Input.GetTouch(0); //첫번째 손가락 터치를 저장
        Touch touch1 = Input.GetTouch(1); //두번째 손가락 터치를 저장

        //deltaPositoin: 이전 프레임의 터치 위치와 현 프레임의 터치 위치 차이 나타냄
        //touch0.deltaPosion=현재 터치 위치-이전 터치 위치
        //=====>현재 터치 위치 알면 이전 터치 위치 알 수 있다
        Vector2 preTouchPos0 = touch0.position - touch0.deltaPosition; //deltaPosition는 이동방향 추적할 때 사용
        Vector2 preTouchPos1 = touch1.position - touch1.deltaPosition;

        // 각 프레임에서 터치 사이의 벡터 거리 구함
        float prevTouchDeltaMag = (preTouchPos0 - preTouchPos1).magnitude; //magnitude는 두 점간의 거리 비교(벡터)
        float touchDeltaMag = (touch0.position - touch1.position).magnitude;

        // 거리 차이 구함
        //음수이면 이전 값이 더 작다는 뜻이므로 줌인
        //양수이면 이전 값이 더 크다는 뜻이므로 줌아웃
        float deltaMagnitudeDiff = prevTouchDeltaMag - touchDeltaMag;

        //fieldOfView 최소, 최댓값 제한하며 거리 차이 반영하기
        this.GetComponent<Camera>().fieldOfView = Mathf.Clamp(this.GetComponent<Camera>().fieldOfView, 17f, 130f);
        this.GetComponent<Camera>().fieldOfView += deltaMagnitudeDiff * perspectiveZoomSpeed;       
    }

    private void Move()
    {
        if (this.player.state != HSYEnum.eState.HandAttack)
        {
            tr.position = new Vector3(target.position.x - 0.52f, tr.position.y, target.position.z - 6.56f);
            
            tr.LookAt(target);
        }
        else return;
    }
}

 


테스트

안드로이드 기기로 테스트한 결과 생각한 대로 잘 돌아갔다

근데 생각보다 줌인 줌아웃이 빠르게 돼서 zoomSpeed는 더 줄이는 편이 좋을 것 같음


새롭게 알게 된 점

1. Touch가 구조체라는 것

2. deltaPosition 프로퍼티의 정의와 활용 방법

deltaPosition=현재 터치 위치-이전 터치 위치

이전 프레임의 터치 위치와 현 프레임의 터치 위치 차이 나타낸다

따라서 현재 터치 위치 알면 이전 터치 위치 알 수 있다


참고

https://dooding.tistory.com/9

 

[Unity] 손가락 터치 줌인/줌아웃

안녕하세요 슐리반입니다. 오늘은 유니티를 이용해 손가락 터치를 입력받아 줌인/줌아웃을 구현하도록 하겠습니다. 줌인,줌아웃은 유니티 공식 홈페이지에서 튜토리얼로 제공하고 있으며, 코

dooding.tistory.com