您当前的位置: 首页 >  unity

程序员正茂

暂无认证

  • 2浏览

    0关注

    283博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Unity3d拖动标题栏移动对话框(面板)

程序员正茂 发布时间:2020-12-21 14:32:46 ,浏览量:2

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;

//通过拖动标题栏移动对话框(面板)
public class DragDialogByTitleBar : MonoBehaviour, IPointerDownHandler, IDragHandler{
	
    //鼠标按下位置
	private Vector2 _ptStartMousePoint;

    //对话框(面板)初始位置
    private Vector3 _ptStartDialogPoint;

    //对话框(面板)
    private RectTransform _dlgRt;

    //对话框(面板)父实体
    private RectTransform _dlgParentRt;
	
	void Awake () {
		_dlgRt = transform.parent as RectTransform;
		_dlgParentRt = _dlgRt.parent as RectTransform;
	}
	
    //按下鼠标
	public void OnPointerDown (PointerEventData data) {
		_ptStartDialogPoint = _dlgRt.localPosition;
		RectTransformUtility.ScreenPointToLocalPointInRectangle (_dlgParentRt, data.position, data.pressEventCamera, out _ptStartMousePoint);
	}
	
    //拖拽
	public void OnDrag (PointerEventData data) {
		if (_dlgRt == null || _dlgParentRt == null)
			return;
		
		Vector2 localPointerPosition;
		if (RectTransformUtility.ScreenPointToLocalPointInRectangle (_dlgParentRt, data.position, data.pressEventCamera, out localPointerPosition)) {
			Vector3 offsetToOriginal = localPointerPosition - _ptStartMousePoint;
			_dlgRt.localPosition = _ptStartDialogPoint + offsetToOriginal;
		}
		
		ClampToWindow ();
	}
	
	//将窗口限定在屏幕内
	void ClampToWindow () {
		Vector3 pos = _dlgRt.localPosition;
		
		Vector3 minPosition = _dlgParentRt.rect.min - _dlgRt.rect.min;
		Vector3 maxPosition = _dlgParentRt.rect.max - _dlgRt.rect.max;
		
		pos.x = Mathf.Clamp (_dlgRt.localPosition.x, minPosition.x, maxPosition.x);
		pos.y = Mathf.Clamp (_dlgRt.localPosition.y, minPosition.y, maxPosition.y);
		
		_dlgRt.localPosition = pos;
	}
}

 

关注
打赏
1660743125
查看更多评论
立即登录/注册

微信扫码登录

0.0414s