안녕하세요 슐리반입니다.
오늘도 손가락 제스처를 구현해보려고 합니다.
저번 포스팅 때 손가락 터치를 이용해서 줌인/줌아웃을 구현한 적이 있는데요.
이번에는 두 손가락을 이용해서 카메라 이동을 구현해볼게요.
구글링을 해보았으나 생각보다 자료가 많이 안나왔어요,
그래서 한 손가락으로 카메라 이동 구현한 코드를 응용했어요.
우선 한 손가락으로 터치 드래그하여 카메라 이동시키는 코드입니다.
using UnityEngine;
using System.Collections;
public class OneTouchCameraMoveManager : MonoBehaviour
{
private float Speed = 0.25f;
private Vector2 nowPos, prePos;
private Vector3 movePos;
void Update()
{
if(Input.touchCount == 1)
{
Touch touch = Input.GetTouch (0);
if(touch.phase == TouchPhase.Began)
{
prePos = touch.position - touch.deltaPosition;
}
else if(touch.phase == TouchPhase.Moved)
{
nowPos = touch.position - touch.deltaPosition;
movePos = (Vector3)(prePos - nowPos) * Time.deltaTime * Speed;
camera.transform.Translate(movePos);
prePos = touch.position - touch.deltaPosition;
}
}
}
}
참고한 코드는 아래 출처로 남겨놓습니다.
[ 출처 ]
[유니티]C# 터치 드래그와 Transform 클래스 : http://vividmani.blogspot.com/2014/06/transform.html
다음은 두 손가락으로 터치 드래그하여 카메라를 이동시킵니다.
using UnityEngine;
using System.Collections;
public class OneTouchCameraMoveManager : MonoBehaviour
{
private float Speed = 0.25f;
private Vector2 nowPos, prePos;
private Vector3 movePos;
void Update()
{
if(Input.touchCount == 2)
{
Touch touchZero = Input.GetTouch(0);
Touch touchOne = Input.GetTouch(1);
if (touchZero.phase == TouchPhase.Began || touchOne.phase == TouchPhase.Began)//터치 시작하면
{
prePos = ((touchZero.position + touchOne.position) / 2) - ((touchZero.deltaPosition + touchOne.deltaPosition) / 2);
}
else if (touchZero.phase == TouchPhase.Moved || touchOne.phase == TouchPhase.Moved)//드래그 중이면
{
nowPos = ((touchZero.position + touchOne.position) / 2) - ((touchZero.deltaPosition + touchOne.deltaPosition) / 2);
movePos = (Vector3)(prePos - nowPos);
GetComponent<Camera>().transform.Translate(movePos * Time.deltaTime * Speed);
prePos = ((touchZero.position + touchOne.position) / 2) - ((touchZero.deltaPosition + touchOne.deltaPosition) / 2);
}
}
}
}
touchZero의 좌표와 touchOne의 좌표를 더해주고 2로 나눠서 두 손가락이 터치된 좌표의 중앙값을 구했습니다.
그러면 카메라는 두 손가락의 위치좌표 중 어느 곳에도 치우치지 않고 중앙 좌표를 기준으로 이동하게 됩니다.
스크립트는 Main Camera에 추가합니다.
그리고 실행하면 두 손가락으로 화면을 드래그시 카메라가 이동하는 모습을 확인할 수 있습니다.
터치 드래그이다 보니까 apk을 제작해서 테스트해야합니다.
apk 제작하는 방법은 제 블로그에 포스팅 되어 있으니 참고하시길 바랍니다.
[현재 진행 사항_(2020년 7월29일)]
두 손가락으로 줌인, 줌아웃도 되고 카메라 이동도 되면서,
한 손가락으로는 오브젝트 회전을 구현하고 싶은데...
두 손가락으로 줌과 카메라 이동 제어를 구분하는 조건을 제어하기가 까다롭네요
해결하면 이것도 포스팅하겠습니다.
그럼 다음 포스팅때 만나요!
이상 슐리반이었습니다.
'개발 > Unity' 카테고리의 다른 글
[Unity] Visual Studio와 Unity 연결하는 방법 (5) | 2021.04.13 |
---|---|
[Unity] 2차원 배열 inspector 창에서 보여주기 (2) | 2020.08.19 |
[Unity] 알아두면 유용한 Mathf 클래스 함수 정리 (1) | 2020.07.29 |
[Unity] 안드로이드 APK 빌드하는 방법(ver.2019.2) (7) | 2020.07.29 |
[Unity] 카메라 Perspective와 Orthographic 모드 비교 (4) | 2020.07.29 |