본문 바로가기
개발/Unity

Unity) UIObject Drag And Drop (UI오브젝트 드래그 앤 드랍)

by 테샤르 2023. 12. 20.

UIObject Drag And Drop (UI오브젝트 드래그 앤 드랍)

간단하게 UI Object를 Drag & Drop 하는 코드를 포스팅한다.

 

반응형

 

<코드>

using UnityEngine.EventSystems;

public class Item : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IDragHandler, IDropHandler
{

private bool isDragging = false;
private Vector2 originalPointerPosition;
private Vector3 originalLocalPosition;
private Vector2 currentDragDelta;
private RectTransform canvasRectTransform;

private void Start()
{
	// Canvas의 RectTransform을 가져옵니다.
	canvasRectTransform = GetComponentInParent<Canvas>().GetComponent<RectTransform>();
}

public void OnPointerDown(PointerEventData eventData)
{
	// 터치 시작 시 호출됩니다.
	isDragging = true;

	RectTransformUtility.ScreenPointToLocalPointInRectangle(
		transform.parent.GetComponent<RectTransform>(),
		eventData.position,
		eventData.pressEventCamera,
		out originalPointerPosition);

	originalLocalPosition = transform.localPosition;
}

public void OnPointerUp(PointerEventData eventData)
{
	// 터치 종료 시 호출됩니다.
	if (isDragging)
		isDragging = false;
	currentDragDelta = Vector2.zero; // 드래그 종료 시 초기화
}

public void OnDrag(PointerEventData eventData)
{
	// 터치 중일 때 호출됩니다.
	if (isDragging)
	{
		Vector2 localPointerPosition;
		if (RectTransformUtility.ScreenPointToLocalPointInRectangle(
			canvasRectTransform,
			eventData.position,
			eventData.pressEventCamera,
			out localPointerPosition))
		{
			transform.localPosition = originalLocalPosition + (Vector3)(localPointerPosition - originalPointerPosition);
			currentDragDelta = localPointerPosition - originalPointerPosition; // 드래그한 값 저장
		}
	}
}

public void OnDrop(PointerEventData eventData)
{
	RectTransform parentRectTransform = transform.parent.GetComponent<RectTransform>();

	// RectTransform의 local 좌표계로 변환
	Vector2 fixedLocalPosition;
	if (RectTransformUtility.ScreenPointToLocalPointInRectangle(
		parentRectTransform,
		eventData.position,
		eventData.pressEventCamera,
		out fixedLocalPosition))
	{
		transform.localPosition = fixedLocalPosition;
	}
}
}

 

반응형

 

Unity iPointerClickHandler : [링크]

 

Unity - Scripting API: IPointerClickHandler

You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see: You've told us there are code samples on this page which don't work. If you know ho

docs.unity3d.com

 

RectTransformUtility -ScreenPointToLocalPointInRectangle : [링크]

 

Unity - Scripting API: RectTransformUtility.ScreenPointToLocalPointInRectangle

The cam parameter should be the camera associated with the screen point. For a RectTransform in a Canvas set to Screen Space - Overlay mode, the cam parameter should be null. When ScreenPointToLocalPointInRectangle is used from within an event handler that

docs.unity3d.com

 

 

★☆☆☆☆

 

반응형

댓글