안녕하세요 슐리반입니다.
오늘은 유니티를 이용해 손가락 터치를 입력받아 줌인/줌아웃을 구현하도록 하겠습니다.
줌인,줌아웃은 유니티 공식 홈페이지에서 튜토리얼로 제공하고 있으며, 코드는 아래에 있습니다.
간단한 주석과 함께 적어놓았으며, 더 자세한 설명과 동영상은 아래 출처에서 확인하실 수 있습니다.
using UnityEngine;
public class PinchZoom : MonoBehaviour
{
public float perspectiveZoomSpeed = 0.5f; //줌인,줌아웃할때 속도(perspective모드 용)
public float orthoZoomSpeed = 0.5f; //줌인,줌아웃할때 속도(OrthoGraphic모드 용)
void Update()
{
if (Input.touchCount == 2) //손가락 2개가 눌렸을 때
{
Touch touchZero = Input.GetTouch(0); //첫번째 손가락 터치를 저장
Touch touchOne = Input.GetTouch(1); //두번째 손가락 터치를 저장
//터치에 대한 이전 위치값을 각각 저장함
//처음 터치한 위치(touchZero.position)에서 이전 프레임에서의 터치 위치와 이번 프로임에서 터치 위치의 차이를 뺌
Vector2 touchZeroPrevPos = touchZero.position - touchZero.deltaPosition; //deltaPosition는 이동방향 추적할 때 사용
Vector2 touchOnePrevPos = touchOne.position - touchOne.deltaPosition;
// 각 프레임에서 터치 사이의 벡터 거리 구함
float prevTouchDeltaMag = (touchZeroPrevPos - touchOnePrevPos).magnitude; //magnitude는 두 점간의 거리 비교(벡터)
float touchDeltaMag = (touchZero.position - touchOne.position).magnitude;
// 거리 차이 구함(거리가 이전보다 크면(마이너스가 나오면)손가락을 벌린 상태_줌인 상태)
float deltaMagnitudeDiff = prevTouchDeltaMag - touchDeltaMag;
// 만약 카메라가 OrthoGraphic모드 라면
if (camera.isOrthoGraphic)
{
camera.orthographicSize += deltaMagnitudeDiff * orthoZoomSpeed;
camera.orthographicSize = Mathf.Max(camera.orthographicSize, 0.1f);
}
else
{
camera.fieldOfView += deltaMagnitudeDiff * perspectiveZoomSpeed;
camera.fieldOfView = Mathf.Clamp(camera.fieldOfView, 0.1f, 179.9f);
}
}
}
}
여기서 카메라 모드는 2가지가 있는데
메인 카메라의 Inspector 창에서 Perspective와 Orthographic 모드 2가지를 확인하실 수 있습니다.
이 부분에 대해서는 다음 포스팅에 올려놨으니 궁금하신 분들은 참고하시길 바라겠습니다.
기본적으로 3D는 Perspective 모드를 사용합니다.
[추가 설명]
Touch.deltaPosition
public Vector2 deltaPosition;
Touch클래스의 deltaPosition 속성은 이전 프레임에서 발생한 터치의 위치와 현재 프레임에서 발생한 터치 위치의 차이를 의미한다.
터치한 화면의 위치가 바뀐 정도를 파악할 수 있어서, 터치의 이동 방향을 추적해야 하는 상황에서 활용할 수 있다.
position은 현재 터치의 위치를 의미함.
공부용 포스팅이라 다양한 의견은 환영입니다.
도움 되었다면 좋아요와 댓글 남겨주세요!
그럼 다음 포스팅때 만나요
이상 슐리반이었습니다.
[출처]
"[unity learn premium]Getting Mobile Input",2020 Unity Technologies
https://learn.unity.com/tutorial/getting-mobile-input
'개발 > Unity' 카테고리의 다른 글
[Unity] 유니티 두 손가락 터치 드래그하여 카메라 이동 구현하기 (2) | 2020.07.29 |
---|---|
[Unity] 알아두면 유용한 Mathf 클래스 함수 정리 (1) | 2020.07.29 |
[Unity] 안드로이드 APK 빌드하는 방법(ver.2019.2) (7) | 2020.07.29 |
[Unity] 카메라 Perspective와 Orthographic 모드 비교 (4) | 2020.07.29 |
두 지점 사이의 중앙 좌표 구하기 (0) | 2020.07.28 |