滑动菜单在游戏中应用广泛,选择人物、关卡。
自己写了一个最基本的滑动菜单,记录下来
头文件中定义如下变量
EventListenerTouchOneByOne* ev;<span style="white-space:pre"> </span>//触摸代理<span style="white-space:pre"> </span>
bool onTouchBegan(Touch* touch, Event* event);<span style="white-space:pre"> </span>//触摸函数
void onTouchMoved(Touch* touch, Event* event);
void onTouchEnded(Touch* touch, Event* event);
Node* background;<span style="white-space:pre"> </span>//需要移动的NODE节点,所有要移动的组件,都添加到这个节点中
cocos2d::Point touch1;<span style="white-space:pre"> </span>// 记录 第一个触摸点
cocos2d::Point touch2;<span style="white-space:pre"> </span>// 记录 第二个触摸点 也可不用这个变量
void ChoseNinjaScene::onEnter()
{
Layer::onEnter();
//设置触摸函数
ev = EventListenerTouchOneByOne::create();
ev->setSwallowTouches(true);
ev->onTouchBegan = CC_CALLBACK_2(ChoseNinjaScene::onTouchBegan, this);
ev->onTouchMoved = CC_CALLBACK_2(ChoseNinjaScene::onTouchMoved, this);
ev->onTouchEnded = CC_CALLBACK_2(ChoseNinjaScene::onTouchEnded, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(ev, this);
}
onExit()函数中 在界面关闭后移除 触摸代理
void ChoseNinjaScene::onExit()
{
Layer::onExit();
_eventDispatcher->removeEventListener(ev);
}
接着对于触摸函数进行具体设置
void ChoseNinjaScene::onTouchEnded(Touch* touch, Event* event)
{
touch2 = touch->getLocation();
float x = touch1.x - touch2.x;
if (x <= -30)
{ //往右移
if (background->getPositionX() != 0)
{
if (background->getPositionX() + 524 <= 0)// +移动距离
{
background->runAction(MoveBy::create(0.5, Vec2(524, 0)));
}
}
}
else if(x >= 30)
{
if (background->getPositionX() - 524 >= -4192 ) //移动距离 * 需要移动的次数(8); 往左移
{
log("zuo : 2");
background->runAction(MoveBy::create(0.5, Vec2(-524, 0)));
}
}
}