Canvas 에서 Screen Space -  Camera 일 경우 마우스 클릭 위치에 UI를 옮기고 싶으면 아래와 같이 하면 됨.

 

ContextMenuEx 스크립트를 만듬.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ContextMenuEx : MonoBehaviour
{
    public RectTransform targetRectTr;
    public Camera uiCamera;
    public RectTransform menuUITr;

    private Vector2 screenPoint;
    private void Start()
    {
        targetRectTr = GetComponent<RectTransform>();
        uiCamera = Camera.main;
    }
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Mouse0))
        {
            RectTransformUtility.ScreenPointToLocalPointInRectangle(targetRectTr, Input.mousePosition, uiCamera, out screenPoint);
            menuUITr.localPosition = screenPoint;
        }
    }
}

 

회색으로 색칠된 UI가 Panel, 빨간색으로 색칠된 UI가 menuUI이다.

마우스 클릭시 클릭된 위치에 menuUI가 잘 나온다.

 

 

패널 바깥부분 누르면 튀어나옴. Panel영역 안에서만 나오게 하고 싶으면 RectTransformUtility.RectangleContainsScreenPoint()함수를 이용하면 됨.

 

Panel영역 내에서만 나타나게 하는 코드

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ContextMenuEx : MonoBehaviour
{
    // RectTransform 범위
    public RectTransform targetRectTr;
    public Camera uiCamera;
    public RectTransform menuUITr;

    private Vector2 screenPoint;
    private void Start()
    {
        uiCamera = Camera.main;
    }
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Mouse0) &&
            RectTransformUtility.RectangleContainsScreenPoint(targetRectTr, Input.mousePosition, uiCamera))
        {
            RectTransformUtility.ScreenPointToLocalPointInRectangle(targetRectTr, Input.mousePosition, uiCamera, out screenPoint);
            menuUITr.localPosition = screenPoint;
        }
    }
}

 

 

+ Recent posts