类似于苹果设置按钮在屏幕范围内拖拽的效果
/*
* ......................我佛慈悲......................
* _oo0oo_
* o8888888o
* 88"C.J"88
* (| -_- |)
* 0\ = /0
* ___/`---'\___
* .' \\| |// '.
* / \\||| : |||// \
* / _||||| -卍-|||||- \
* | | \\\ - /// | |
* | \_| ''\---/'' |_/ |
* \ .-\__ '-' ___/-. /
* ___'. .' /--.--\ `. .'___
* ."" '< `.___\_<|>_/___.' >' "".
* | | : `- \`.;`\ _ /`;.`/ - ` : | |
* \ \ `_. \_ __\ /__ _/ .-` / /
* =====`-.____`.___ \_____/___.-`___.-'=====
* `=---='
*
*..................佛祖开光 ,永无BUG...................
*
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class DragWindow : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
public float limitLeftRange = 0; //UI到左边界的距离
public float limitRightRange = 0; //UI到右边边界的距离
public float limitTopRange = 0; //UI到顶部边界的距离
public float limitDownRange = 0; //UI到底部边界的距离
private Vector3 offset; //UI和指针的位置偏移量
private RectTransform rt;
private Vector3 pos;
private float minWidth; //水平最小拖拽范围
private float maxWidth; //水平最大拖拽范围
private float minHeight; //垂直最小拖拽范围
private float maxHeight; //垂直最大拖拽范围
private float rangeX; //拖拽范围
private float rangeY; //拖拽范围
void Update()
{
DragRangeLimit();
}
void Start()
{
rt = GetComponent<RectTransform>();
pos = rt.position;
minWidth = rt.rect.width / 2+limitLeftRange;
maxWidth = Screen.width - (rt.rect.width / 2)-limitRightRange;
minHeight = rt.rect.height / 2+limitDownRange;
maxHeight = Screen.height - (rt.rect.height / 2)-limitTopRange;
}
/// <summary>
/// 拖拽范围限制
/// </summary>
void DragRangeLimit()
{
//限制水平/垂直拖拽范围在最小/最大值内
rangeX = Mathf.Clamp(rt.position.x, minWidth, maxWidth);
rangeY = Mathf.Clamp(rt.position.y, minHeight, maxHeight);
//更新位置
rt.position = new Vector3(rangeX, rangeY, 0);
}
/// <summary>
/// 开始拖拽
/// </summary>
public void OnBeginDrag(PointerEventData eventData)
{
Vector3 globalMousePos;
//将屏幕坐标转换成世界坐标
if (RectTransformUtility.ScreenPointToWorldPointInRectangle(rt, eventData.position, null, out globalMousePos))
{
//计算UI和指针之间的位置偏移量
offset = rt.position - globalMousePos;
}
}
/// <summary>
/// 拖拽中
/// </summary>
public void OnDrag(PointerEventData eventData)
{
SetDraggedPosition(eventData);
}
/// <summary>
/// 结束拖拽
/// </summary>
public void OnEndDrag(PointerEventData eventData)
{
}
/// <summary>
/// 更新UI的位置
/// </summary>
private void SetDraggedPosition(PointerEventData eventData)
{
Vector3 globalMousePos;
if (RectTransformUtility.ScreenPointToWorldPointInRectangle(rt, eventData.position, null, out globalMousePos))
{
rt.position = offset + globalMousePos;
}
}
}
上面代码开始运行是没有任何问题,是在屏幕设置范围内运动,但是当改变屏幕分辨率的时候就出现了问题,这个和Canva有关,于是更改了一个版本,无论怎么更改分辨率也是没有问题的。
代码连接: