/*******************************************************************************
* 版本声明:v1.0.0
* 类 名 称: DragUI
* 创建日期:2020-07-29 10:36:36
* 作者名称:静哥哥
* CLR 版本:4.0.30319.42000
* 修改记录:
* 描述:拖拽UI
******************************************************************************/
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
using UnityEngine.UI;
namespace Com.Rainier.WangJing
{
public class DragUI : MonoBehaviour,IDragHandler,IBeginDragHandler
{
private Vector3 worldPos;
private Vector3 offset;
void Start()
{
}
public void OnDrag(PointerEventData eventData)
{
transform.position = offset + Input.mousePosition;
}
public void OnBeginDrag(PointerEventData eventData)
{
if (RectTransformUtility.ScreenPointToWorldPointInRectangle(transform.GetComponent<RectTransform>(), Input.mousePosition
, eventData.enterEventCamera, out worldPos))
{
offset = transform.position - worldPos;
}
}
void Update()
{
DragRangeLimit(transform);
}
/// <summary>
/// 限制移动距离在屏幕内
/// </summary>
/// <param name="tra"></param>
public void DragRangeLimit(Transform tra)
{
var pos = tra.GetComponent<RectTransform>();
float x = Mathf.Clamp(pos.position.x, pos.rect.width * 0.5f, Screen.width - (pos.rect.width * 0.5f));
float y = Mathf.Clamp(pos.position.y, pos.rect.height * 0.5f, Screen.height - (pos.rect.height * 0.5f));
pos.position = new Vector2(x, y);
}
}
}
Unity实现UGUI拖拽及控制拖拽不出屏幕
最新推荐文章于 2024-04-25 17:51:16 发布