Skip to content

Instantly share code, notes, and snippets.

@gamebox777 gamebox777/DraggableUI.cs

Last active Nov 27, 2019
Embed
What would you like to do?
ドラッグする部分(タイトルバー)にAddするスクリプト
//public domain(著作権破棄) ご自由にお使いください
// 説明ページはこちら↓
// http://www.unitygamebox.com/entry/2019/11/27/%E3%80%90unity%E3%80%91%E3%83%89%E3%83%A9%E3%83%83%E3%82%B0/%E7%B8%AE%E5%B0%8F/%E6%9C%80%E5%A4%A7%E5%8C%96%E3%81%A7%E3%81%8D%E3%82%8B%E3%82%A6%E3%82%A3%E3%83%B3%E3%83%89%E3%82%A6%E3%80%90%E3%82%B9
using UnityEngine;
using UnityEngine.EventSystems;
using System;
using System.Collections;
namespace DragWindow
{
/// <summary>
/// ドラッグするウィンドウ
/// ※オーバーレイキャンバスのみ使用可
/// </summary>
[Serializable]
public partial class DraggableUI : MonoBehaviour, IDragHandler
{
[SerializeField] public RectTransform targetTransform;
[SerializeField] public bool BlockScreenOut; //スクリーンから出ないようにする設定
[SerializeField] public float padding = 30;
[NonSerialized] public RectTransform rect;
protected virtual void Awake()
{
rect = GetComponent<RectTransform>();
if (targetTransform == null){ targetTransform = rect; }
}
public virtual void OnDrag(PointerEventData e)
{
if (BlockScreenOut)
{
var c1 = rect.TransformPoint(new Vector3(rect.rect.x, rect.rect.y, 0));
var c2 = rect.TransformPoint(new Vector3(rect.rect.xMax, rect.rect.yMax, 0));
var delta = e.delta;
if (c2.x + delta.x < padding) { delta.x = padding - c2.x; }
if (c1.x + delta.x > Screen.width - padding) { delta.x = Screen.width - padding - c1.x; }
if (c2.y + delta.y < padding) { delta.y = padding - c2.y; }
if (c1.y + delta.y > Screen.height - padding) { delta.y = Screen.height - padding - c1.y; }
targetTransform.position += (Vector3)delta;
}
else
{
targetTransform.position += (Vector3)e.delta;
}
}
}
} //namespace:DragWindow
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.