오르막길

[Unity] 마우스 좌표(mousePosition)을 UI (Canvas)좌표로 바꾸기 본문

학습 기록하기/Unity

[Unity] 마우스 좌표(mousePosition)을 UI (Canvas)좌표로 바꾸기

nanalyee 2023. 9. 22. 11:14

Goal

mousePosition을 Canvas 좌표로 바꾸어 보자

Problem

시작 지점을 단순히 startPos = Input.moustPosition으로 했더니 캔버스의 중심좌표 (정가운데)에서 생성되는 문제

Cause & Solution

RectTransformUtility.ScreenPointToLocalPointInRectangle

 

RectTransformUtility.ScreenPointToLocalPointInRectangle

RectTransformUtility.ScreenPointToLocalPointInRectangle public static bool ScreenPointToLocalPointInRectangle(RectTransform rect, Vector2 screenPoint, Camera cam, out Vector2 localPoint); ScreenPoint(스크린좌표)를 RectTransform의 LocalPoint(캔버

flowtree.tistory.com

https://docs.unity3d.com/ScriptReference/RectTransformUtility.ScreenPointToLocalPointInRectangle.html

 

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

RectTransformUtility.ScreenPointToLocalPointInRectangle

공식 문서와 어떤 분이 정리하신 글을 참고했다.

Camera의 매개 변수는 ScreenPoint(스크린 좌표)와 연관된 카메라이어야 한다.

캔버스에서 RectTransform이 Screen Space-Overlay 모드로 설정된 경우 cam 매개 변수는 null 이어야 한다.

 

예시) RectTransformUtility.ScreenPointToLocalPointInRectangle(rectParent, Input.mousePosition, null, out startPos);

→ rectParent = canvas.GetComponent<RectTransform>();

→ Screen Space-Overlay 모드를 사용중이기 때문에 null

→ 시작할 좌표 (나 같은 경우, 사각형 그리기가 시작될 좌표)는 Vector2 startPos;