Files
EnglewoodLAB/Assets/Scripts/UI/SettingPanel/Dragger.cs
SOOBEEN HAN f1894889ee <refactor> Octopus Twin 템플릿 적용
- 기능 외 UI 구조만 적용
- 프로젝트에 걸맞는 UI는 재작업 필요
2026-02-23 18:20:09 +09:00

97 lines
3.2 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
namespace CHN
{
public class Dragger : MonoBehaviour, IBeginDragHandler, IDragHandler
{
[Header("Resources")]
public RectTransform dragArea;
public RectTransform dragObject;
[Header("Settings")]
public bool topOnDrag = true;
private Vector2 originalLocalPointerPosition;
private Vector3 originalPanelLocalPosition;
public void Awake()
{
if (dragArea == null)
{
try
{
var canvas = transform.GetComponentInParent<Canvas>();
dragArea = canvas.GetComponent<RectTransform>();
}
catch { Debug.LogError("<b>[Movable Window]</b> Drag Area has not been assigned."); }
}
}
private RectTransform DragObjectInternal
{
get
{
if (dragObject == null) { return (transform as RectTransform); }
else { return dragObject; }
}
}
private RectTransform DragAreaInternal
{
get
{
if (dragArea == null)
{
RectTransform canvas = transform as RectTransform;
while (canvas.parent != null && canvas.parent is RectTransform) { canvas = canvas.parent as RectTransform; }
return canvas;
}
else { return dragArea; }
}
}
public void OnBeginDrag(PointerEventData data)
{
if (!Input.GetMouseButton(0))
return;
originalPanelLocalPosition = DragObjectInternal.localPosition;
RectTransformUtility.ScreenPointToLocalPointInRectangle(DragAreaInternal, data.position, data.pressEventCamera, out originalLocalPointerPosition);
gameObject.transform.SetAsLastSibling();
if (topOnDrag == true) { dragObject.transform.SetAsLastSibling(); }
}
public void OnDrag(PointerEventData data)
{
if (!Input.GetMouseButton(0))
return;
Vector2 localPointerPosition;
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(DragAreaInternal, data.position, data.pressEventCamera, out localPointerPosition))
{
Vector3 offsetToOriginal = localPointerPosition - originalLocalPointerPosition;
DragObjectInternal.localPosition = originalPanelLocalPosition + offsetToOriginal;
}
ClampToArea();
}
private void ClampToArea()
{
Vector3 pos = DragObjectInternal.localPosition;
Vector3 minPosition = DragAreaInternal.rect.min - DragObjectInternal.rect.min;
Vector3 maxPosition = DragAreaInternal.rect.max - DragObjectInternal.rect.max;
pos.x = Mathf.Clamp(DragObjectInternal.localPosition.x, minPosition.x, maxPosition.x);
pos.y = Mathf.Clamp(DragObjectInternal.localPosition.y, minPosition.y, maxPosition.y);
DragObjectInternal.localPosition = pos;
}
}
}