欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

NGUI实现滑动翻页效果实例代码

程序员文章站 2022-11-23 22:50:02
废话不多说了,直接给大家上干货了。 具体代码如下所示: using unityengine; using system.collections; publi...

废话不多说了,直接给大家上干货了。

具体代码如下所示:

using unityengine;
using system.collections;
public class pageview : monobehaviour
{
const int item_num = 2; //总页数
const int page_width = 2048; //页宽
const float drag_speed = 0.5f; //翻页时间
const int drag_offect = 30; //滑动的起点和终点的差需大于这个数才能触发翻页效果
float beganx = 0; 
float begany = 0; //鼠标按下的坐标
int curindex = 1; //当前页数,默认为第一页
bool isplay = false; //是否正在翻页
bool ispress = false; //鼠标是否按下
bool ispagefoot = false; //当前是否处于页尾
bool ishomepage = true; //当前是否处于首页
string left = "left"; //左滑动画的name
string right = "right"; //右滑动画的name
gameobject[] item_objects;
// use this for initialization
void start ()
{
this.init ();
}
void init()
{
item_objects = new gameobject[item_num];
for(int i = 1; i <= item_num; ++i)
{
transform trans = this.transform.findchild("item" + i);
if(trans)
{
gameobject spr = trans.transform.findchild("background").gameobject;
spr.addcomponent<uieventlistener>();
uieventlistener.get(spr.gameobject).onpress = onpressevent;
}
item_objects[i - 1] = trans.gameobject;
}
}
//鼠标按下事件监听
void onpressevent(gameobject obj,bool isdown)
{
float endx;
float endy;
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();
}
}else if(endx - beganx < drag_offect){
if(ispagefoot == false)
{
leftdrag();
}
}
}
}
ispress = false;
}
}
//向左滑
void leftdrag()
{
isplay = true;
float x = this.transform.localposition.x - page_width;
tweenposition lefttween = tweenposition.begin (this.gameobject,drag_speed,new vector3(x,0,0));
lefttween.method = uitweener.method.easeinout;
lefttween.callwhenfinished = "callback";
lefttween.name = left;
lefttween.reset ();
}
//向右滑
void rightdrag()
{
isplay = true;
float x = this.transform.localposition.x + page_width;
tweenposition righttween = tweenposition.begin (this.gameobject,drag_speed,new vector3(x,0,0));
righttween.method = uitweener.method.easeinout;
righttween.callwhenfinished = "callback";
righttween.name = right;
righttween.reset ();
}
//动画结束的回调函数
void callback(uitweener tween)
{
isplay = false;
if (tween.name == left) 
{
curindex ++;
} else if (tween.name == right) 
{
curindex --;
}
if (curindex == 1) 
{
ishomepage = true;
}else
{
ishomepage = false;
}
if(curindex == item_num){
ispagefoot = true;
}else
{
ispagefoot = false;
}
}
}

代码到此结束了,如果大家对代码有疑问欢迎给我留言,小编会及时和大家取得联系的。同时也非常感谢大家对网站的支持!