본문 바로가기
[Unity]

[Unity] 마우스 위치를 UI 요소의 로컬 좌표로 변환하기

by 김기승 2023. 9. 28.

RectTransformUtility 클래스의 ScreenPointToLocalPointInRectangle 함수로 쉽게 구할 수 있다.

함수의 구조는 아래와 같다.

 public static bool ScreenPointToLocalPointInRectangle(RectTransform rect, Vector2 screenPoint, Camera cam, out Vector2 localPoint

ImageCanvas(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) 

댓글