NGUI实现滑动翻页效果实例代码
废话不多说了,直接给大家上干货了。
具体代码如下所示:
usingUnityEngine;
usingSystem.Collections;
publicclassPageView:MonoBehaviour
{
constintITEM_NUM=2;//总页数
constintPAGE_WIDTH=2048;//页宽
constfloatDRAG_SPEED=0.5f;//翻页时间
constintDRAG_OFFECT=30;//滑动的起点和终点的差需大于这个数才能触发翻页效果
floatbeganX=0;
floatbeganY=0;//鼠标按下的坐标
intcurIndex=1;//当前页数,默认为第一页
boolisPlay=false;//是否正在翻页
boolisPress=false;//鼠标是否按下
boolisPageFoot=false;//当前是否处于页尾
boolisHomePage=true;//当前是否处于首页
stringleft="left";//左滑动画的name
stringright="right";//右滑动画的name
GameObject[]Item_Objects;
//Usethisforinitialization
voidStart()
{
this.Init();
}
voidInit()
{
Item_Objects=newGameObject[ITEM_NUM];
for(inti=1;i<=ITEM_NUM;++i)
{
Transformtrans=this.transform.FindChild("item"+i);
if(trans)
{
GameObjectspr=trans.transform.FindChild("Background").gameObject;
spr.AddComponent<UIEventListener>();
UIEventListener.Get(spr.gameObject).onPress=OnPressEvent;
}
Item_Objects[i-1]=trans.gameObject;
}
}
//鼠标按下事件监听
voidOnPressEvent(GameObjectobj,boolisDown)
{
floatendX;
floatendY;
if(isDown)
{
beganX=UICamera.lastTouchPosition.x;
beganY=UICamera.lastTouchPosition.y;
isPress=true;
}else
{
endX=UICamera.lastTouchPosition.x;
endY=UICamera.lastTouchPosition.y;
if(isPress)
{
if(isPlay==false)
{
if(endX-beganX>DRAG_OFFECT)
{
if(isHomePage==false)
{
RightDrag();
}
}elseif(endX-beganX<DRAG_OFFECT){
if(isPageFoot==false)
{
LeftDrag();
}
}
}
}
isPress=false;
}
}
//向左滑
voidLeftDrag()
{
isPlay=true;
floatx=this.transform.localPosition.x-PAGE_WIDTH;
TweenPositionleftTween=TweenPosition.Begin(this.gameObject,DRAG_SPEED,newVector3(x,0,0));
leftTween.method=UITweener.Method.EaseInOut;
leftTween.callWhenFinished="callback";
leftTween.name=left;
leftTween.Reset();
}
//向右滑
voidRightDrag()
{
isPlay=true;
floatx=this.transform.localPosition.x+PAGE_WIDTH;
TweenPositionrightTween=TweenPosition.Begin(this.gameObject,DRAG_SPEED,newVector3(x,0,0));
rightTween.method=UITweener.Method.EaseInOut;
rightTween.callWhenFinished="callback";
rightTween.name=right;
rightTween.Reset();
}
//动画结束的回调函数
voidcallback(UITweenertween)
{
isPlay=false;
if(tween.name==left)
{
curIndex++;
}elseif(tween.name==right)
{
curIndex--;
}
if(curIndex==1)
{
isHomePage=true;
}else
{
isHomePage=false;
}
if(curIndex==ITEM_NUM){
isPageFoot=true;
}else
{
isPageFoot=false;
}
}
}
代码到此结束了,如果大家对代码有疑问欢迎给我留言,小编会及时和大家取得联系的。同时也非常感谢大家对毛票票网站的支持!