标签:blog http io os ar for sp div 2014
NGUI 提供了非常丰富、强大的组件库,其中就包括 UIDragObject 组件,这个组件用来实现面板的拖动效果,但是这个组件有一个不好的地方就是被拖动的对象可以被拖到屏幕之外,不过我们可以很容易的借助 NGUI 的代码类库进行来修复这个问题。
我们先看一下 NGUI 自带的 UIDragObject 组件如何实现面板的拖动。
第一步先布局好界面,如图:

然后我们给可拖动的对象(Background)添加 UIDragObject 组件,如图:

接着设置 UIDragObject 的 Target 属性为 Background,如图:

到这儿我们先运行一下,看看效果,这时候我们是无法拖动面板的,究其原因很简单,我们没有给 Background 添加 Collider,如图:

下面,我们给 Background 添加 Box Collider,如图:

设置好 Box Collider 的 Size 信息,如图:

这时候我们再次运行,就可以看到,我们可以拖动面板了,但是我们也可以发现,我们可以把面板拖到屏幕之外,如图:

下面我们就去修复这个问题,我们先去掉 UIDragObject 组件,如图:

接着我们新建立一个 C# 类,取名 UDragManager.cs,如图:

然后我们编写 UDragManager.cs 类,具体代码如下:
using UnityEngine;
using System.Collections;
public class UDragManager : MonoBehaviour
{
public Transform target;
private Vector3 offset;
private Bounds bounds;
void OnPress(bool pressed)
{
if (target == null) return;
if (pressed)
{
bounds = NGUIMath.CalculateRelativeWidgetBounds(target.transform);
Vector3 position = UICamera.currentCamera.WorldToScreenPoint(target.position);
offset = new Vector3(Input.mousePosition.x - (position.x - bounds.size.x / 2), Input.mousePosition.y - (position.y - bounds.size.y / 2),0f);
}
}
void OnDrag(Vector2 delta)
{
Vector3 currentPoint = new Vector3 (Input.mousePosition.x - offset.x, Input.mousePosition.y - offset.y, 0f);
//如果坐标小于0
if (currentPoint.x < 0)
{
currentPoint.x = 0;
}
//如果坐标大于屏幕宽
if (currentPoint.x + bounds.size.x > Screen.width)
{
currentPoint.x = Screen.width - bounds.size.x;
}
//如果坐标小于0
if (currentPoint.y < 0)
{
currentPoint.y = 0;
}
//如果坐标大于屏幕高
if (currentPoint.y + bounds.size.y > Screen.height)
{
currentPoint.y = Screen.height - bounds.size.y;
}
currentPoint.x += bounds.size.x / 2;
currentPoint.y += bounds.size.y / 2;
target.position = UICamera.currentCamera.ScreenToWorldPoint (currentPoint);
}
}
接下来,我们再给 Background 添加 UDragManager 类,如图:

并且设置好 UDragManager 的 Target 属性为 Background,如图:

这时候我们再次运行,看看最终的效果,这时候我们已经把面板限制在屏幕中间了,其实我们还可以把面板限制在屏幕中的一块区域中,只需要修改区域判定的代码就可以了,最终效果图如下:

原文链接地址:http://www.omuying.com/article/40.aspx
标签:blog http io os ar for sp div 2014
原文地址:http://www.cnblogs.com/snipen/p/4021416.html