오르막길
[Unity] 마우스 좌표(mousePosition)을 UI (Canvas)좌표로 바꾸기 본문
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
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;
'학습 기록하기 > Unity' 카테고리의 다른 글
| [Unity] 상태 패턴 (State Pattern) 알아보기 (0) | 2025.05.26 |
|---|---|
| [Unity] 쉽게 할 수 있는 최적화 팁들 (+추가 예정) (0) | 2025.04.28 |
| [Unity] 유니티 시네머신 훑어보기: 다양한 카메라 연출을 위한 필수 기능 (0) | 2025.03.31 |
| [Unity] 유니티 WebGL 빌드 파일을 Nginx 기반 로컬에서 테스트해보자 (0) | 2024.01.09 |
| [Unity] 유니티에서 WebGL 템플릿을 직접 커스텀해보자: WebGL Custom Templete (0) | 2023.11.22 |