RectTransformUtility 클래스의 ScreenPointToLocalPointInRectangle 함수로 쉽게 구할 수 있다.
함수의 구조는 아래와 같다.
public static bool ScreenPointToLocalPointInRectangle(RectTransform rect, Vector2 screenPoint, Camera cam, out Vector2 localPoint) |

Image를 Canvas(1600x900)에 생성한 후, 아래의 코드를 적용하였다.
using UnityEngine;
public class RTUtil : MonoBehaviour
{
public RectTransform rt;
private void Update()
{
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(rt, Input.mousePosition, null, out Vector2 localPoint))
{
Debug.Log($"localPoint : {localPoint}"); //로컬 좌표 디버깅
}
}
}
※ cam 파라미터를 굳이 넣어줄 필요는 없다.

결과적으로, 마우스 위치를 특정 RectTransform의 로컬 좌표로 변환한 것을 볼 수 있다.
※ 로컬 좌표이므로 localScale에 영향을 받는다는 것을 명심하자.
만약, 단지 마우스가 UI 요소에 걸쳐있는지만 판단하고싶으면, 아래의 함수를 활용하자.
public static bool RectangleContainsScreenPoint(RectTransform rect, Vector2 screenPoint, Camera cam) |
'[Unity]' 카테고리의 다른 글
[Unity] GL로 카메라 페이드 효과 구현하기 (51) | 2023.10.05 |
---|---|
[Unity] WebGL 빌드 시 웹 페이지에서 키보드 입력받기 (37) | 2023.10.03 |
[Unity] 모바일 플랫폼의 터치 입력 처리하기 (63) | 2023.09.24 |
[Unity] 코드 조각으로 빠르게 코딩하기 - Code Snippet (51) | 2023.09.23 |
[Unity] FOV(Field of View)에 대해 알아보자 (0) | 2023.09.17 |
댓글