https://docs.unity3d.com/ScriptReference/RectTransformUtility.html
Unity - Scripting API: RectTransformUtility
Success! Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable. Close
docs.unity3d.com
UGUI 에서 RectTransform 의 위치를 가지고 월드좌표, 마우스좌표와 자주 연동시킬 때 많이 쓰는 함수 조금 정리.
RectTransform 이 붙은 게임오브젝트를 (0,0) 에서 width, height (200,200) 으로 위치시켰다.
마우스클릭을 (200,200) 의 거의 끝자락에 했음.
using UnityEngine;
public class RectUtils : MonoBehaviour
{
[SerializeField] private RectTransform rectTransform;
// Update is called once per frame
void Update() {
if (Input.GetMouseButtonDown(0)) {
if (RectTransformUtility.RectangleContainsScreenPoint(rectTransform, Input.mousePosition, null)) {
Debug.Log($"1. ScreenPoint is Contained");
}
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, Input.mousePosition, null, out Vector2 anchoredPosition)) {
Debug.Log($"2. anchoredPosition : {anchoredPosition}");
}
}
}
}
RectangleContainsScreenPoint(rectTransform, Input.mousePosition, null)
ScreenPointToLocalPointInRectangle(rectTransform, Input.mousePosition, null, out Vector2 anchoredPosition)
만약 Canvas Render Mode 가 Overlay 이면 null 로 설정.
살짝 응용하면.
https://tech.pjin.jp/blog/2017/07/14/unity_ugui_sync_rendermode/
【Unity】uGUIをキャラクターの上に表示する手っ取り早い方法【RenderMode別】
uGUIをキャラクターの頭上に表示(HUD)して、オブジェクトの移動に追従させる方法は、CanvasのRenderModeによって異なります。 今回はその実装の手っ取り早い方法について、RenderMode別に解説し
tech.pjin.jp
Canvas Render Mode 를 Camera 로 수정
using UnityEngine;
public class UIController_Camera : MonoBehaviour {
[SerializeField]
private RectTransform canvasRectTfm;
[SerializeField]
private Transform targetTfm;
private RectTransform myRectTfm;
private Vector3 offset = new Vector3(0, 1.5f, 0);
void Start() {
myRectTfm = GetComponent<RectTransform>();
}
void Update() {
Vector2 pos;
Vector2 screenPos = RectTransformUtility.WorldToScreenPoint(Camera.main, targetTfm.position + offset);
RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasRectTfm, screenPos, Camera.main, out pos);
Debug.Log(pos);
myRectTfm.anchoredPosition = pos;
}
}
'Unity' 카테고리의 다른 글
[Unity] Canvas 위에 마우스 위치 가져오기 (0) | 2024.05.08 |
---|---|
[Unity] 윈도우 데스크탑 인스톨러 만들기 (0) | 2023.08.08 |
[Unity] UniTask + Action + Lambda 고찰 (0) | 2023.05.16 |
[Unity] Stencil Buffer 에 대해서 (0) | 2023.04.26 |
[Unity] 커스텀 에디터 사용하기 (0) | 2023.04.14 |