IDragHandler는 유니티에서 UI 드래그를 처리할 때 자주 사용하는 인터페이스 입니다.
이를 사용한 예제를 간단히 보여드리겠습니다.
다음과 같이 코드를 작성하여 드래그를 표현할 수 있습니다.
using UnityEngine;
using UnityEngine.EventSystems;
public class DragTest : MonoBehaviour, IDragHandler
{
private RectTransform _rectTransform;
private void Start()
{
_rectTransform = GetComponent<RectTransform>();
}
public void OnDrag(PointerEventData eventData)
{
if (eventData.button == PointerEventData.InputButton.Right) return;
// Move the object with the mouse
_rectTransform.position = eventData.position;
}
}
위 코드에서는 어떻게 보면 정상적으로 보이지만, 경우에 따라 문제가 발생합니다.
다음과 같이 캔버스에서 일반적으로 사용하는 Scale With Screen Size를 FHD사이즈로 지정한 상태에서 QHD나 UHD해상도로 유니티에서 플레이를 하게 되면 드래그가 고장나는 문제가 발생합니다.
위 문제를 해결하기 위해선 다음과 같은 코드를 통해 해결할 수 있습니다.
다음 코드는 화면 좌표(Screen Point)를 특정 RectTransform 객체의 로컬 좌표(Local Point)로 변환하는 함수입니다.
RectTransformUtility.ScreenPointToLocalPointInRectangle(
dragTargetRectTransform,
eventData.position,
eventData.pressEventCamera,
out var localPoint);
예제 코드는 다음과 같습니다.
using UnityEngine;
using UnityEngine.EventSystems;
public class DragTest : MonoBehaviour, IDragHandler
{
private RectTransform _rectTransform;
private void Start()
{
_rectTransform = GetComponent<RectTransform>();
}
public void OnDrag(PointerEventData eventData)
{
if (eventData.button == PointerEventData.InputButton.Right) return;
RectTransformUtility.ScreenPointToLocalPointInRectangle(_rectTransform, eventData.position, eventData.pressEventCamera, out var localPoint);
_rectTransform.anchoredPosition += localPoint;
}
}