UI 구성요소 마우스로 움직이기 (퍼즐)

2023. 8. 1. 17:44· Unity/2D

 

 

 

Drag and Drop

 

간단하게는 퍼즐 게임부터 UI 간의 상호작용 구현까지 활용 가능한 기능이기때문에 한 번 정리해보기. 안 적어두니까 매 번 만들 때마다 헷갈려서......

 

 

 

 

 


 

 

 

IBeginDragHandler, IDragHandler, IEndDragHandler
public class puzzle : MonoBehaviour, IDragHandler, IEndDragHandler, IBeginDragHandler

 

각각 드래그시작, 진행, 종료 시에 발생하는 이벤트를 호출하는 함수. UI 드래그를 위해 세 개의 인터페이스를 모두 사용한다. 인터페이스를 사용하면 해당 스크립트에서 정리한 함수들을 상속받아 구현이 가능하다.

더보기

https://docs.unity3d.com/kr/530/ScriptReference/EventSystems.IBeginDragHandler.OnBeginDrag.html

https://docs.unity3d.com/kr/530/ScriptReference/EventSystems.IDragHandler.OnDrag.html

https://docs.unity3d.com/kr/530/ScriptReference/EventSystems.IEndDragHandler.OnEndDrag.html

 

 

 

 

 

IBeginDragHandler
public void OnBeginDrag(PointerEventData eventData)
{
    initialPos = gameObject.transform.position;
    rectTR = GetComponent<RectTransform>();
}

 

OnBeginDrag 는 의미 그대로 드래그를 시작할 때 호출되는 함수. 정답이 틀렸거나 이런 저런 조건으로 인해 원래대로 초기화 될 경우를 대비해 현재 퍼즐 조각의 위치를 저장해둔다. (initialPos)

 

 

 

OnDrag
public void OnDrag(PointerEventData eventData)
{
    movingPos = eventData.position;
    movingPos = UIcam.ScreenToWorldPoint(movingPos);

    rectTR.position = movingPos;
    rectTR.localPosition = new Vector3(rectTR.localPosition.x, rectTR.localPosition.y, 0);
}

 

UI 상의 Position과 Mouse의 Position(eventData)은 다른 좌표계에서 움직이기 때문에 하나로 통일해야 한다.

 

Canvas 위에서 UI를 움직이는 상황이기에 편의상 마우스의 위치를 ScreenPoint로 변경해준다. 이때, 사용하는 카메라가 무엇인지 지정을 해주어야 한다. Camera.main.ScreenToWorldPoint 의 경우 유니티상에서 MainCamera로 태깅해준 카메라를 의미하기에, UI를 비추는 카메라가 따로 존재할 경우 바인딩이나 캐싱으로 어느 포인트를 사용할 것인지 알려주어야 한다.

 

에디터상에서는 보이는데, Game(Simulator)화면에서는 보이지 않을 경우 z 축의 depth 문제로 카메라에 잡히지 않는 경우일 수 있기때문에 z 값을 0으로 고정시켜주도록 한다.

 

 

 

OnEndDrag
public void OnEndDrag(PointerEventData eventData)
{
    Debug.Log("DRAG SUCCESS!");
    gameObject.transform.position = initialPos;
}

 

마지막으로 드래그를 마쳤을 때, 조건에 따라 성공 / 실패 여부를 나눠준다. 해당 코드에서는 원래 있던 자리로 되돌아가게끔 구성해두었다.

더보기

전체 코드 보기

private Vector3 initialPos;
private Vector3 movingPos;
private RectTransform rectTR;

[SerializeField] private Camera UIcam = null;

public void OnBeginDrag(PointerEventData eventData)
{
    initialPos = gameObject.transform.position;
    rectTR = GetComponent<RectTransform>();
}
public void OnDrag(PointerEventData eventData)
{
    movingPos = eventData.position;
    movingPos = UIcam.ScreenToWorldPoint(movingPos);

    rectTR.position = movingPos;
    rectTR.localPosition = new Vector3(rectTR.localPosition.x, rectTR.localPosition.y, 0);
}
public void OnEndDrag(PointerEventData eventData)
{
    Debug.Log("DRAG SUCCESS!");
    gameObject.transform.position = initialPos;
}
_키아
_키아
_키아
On Ground
_키아
전체
오늘
어제
  • 분류 전체보기 (28)
    • Error (3)
    • Python (5)
      • NLP (4)
    • Unity (15)
      • 2D (1)
      • 3D (1)
      • VR (1)
      • AR (1)
      • Error (9)
    • Unreal (0)
    • Code (1)
      • Leatcode (0)
      • Baekjoon (0)
    • ETC (3)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • AR
  • scripttemplate
  • 유니티
  • NDK
  • unity6
  • Unity
  • SDK
  • 자연어처리
  • JDK
  • ARFoundation

최근 댓글

최근 글

hELLO · Designed By 정상우.v4.2.1
_키아
UI 구성요소 마우스로 움직이기 (퍼즐)
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.