在Cocos2dx游戏开发中经常会遇到在场景中弹出模态层,并在弹出层中添加按钮的情况。通常做法是在弹出层中添加一个背景颜色遮罩,然后在弹出层将触摸事件吞噬掉,使得在弹出层里处理触摸事件,判断触摸点是否在Button上,以此处理按钮事件。但是这样会出现按钮的显示不正常的问题,即按钮在点击之后会显示禁用的效果,解决防范是创建按钮的时候传入三个图片参数,最后两个参数是按钮点击和禁用时的图片,将他们设置为一样就行了。下面贴出具体代码,并对代码测试。
PopupLayer.h
#ifndef __POPUP_LAYER_H__
#define __POPUP_LAYER_H__
#include "cocos2d.h"
#include "ui/UIButton.h"
typedef enum tagButtonResult
{
ButtonResult_OK = 0
} ButtonResult;
typedef std::function<void(cocos2d::Ref*, ButtonResult)> ButtonTouchedCallback;
class PopupLayer : public cocos2d::Layer
{
public:
// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
virtual bool init() override;
// 触摸事件
virtual bool onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *unused_event);
virtual void onTouchMoved(cocos2d::Touch *touch, cocos2d::Event *unused_event);
virtual void onTouchEnded(cocos2d::Touch *touch, cocos2d::Event *unused_event);
virtual void onTouchCancelled(cocos2d::Touch *touch, cocos2d::Event *unused_event);
// implement the "static create()" method manually
CREATE_FUNC(PopupLayer);
public:
//设置按钮回调函数
void SetCallBackFunc(ButtonTouchedCallback callfunc);
private:
//销毁layer并调用回调函数
void DestroySelf(cocos2d::Ref* sender, ButtonResult result);
//按钮回调函数
void buttonCallback(cocos2d::Ref* sender, cocos2d::ui::Widget::TouchEventType event);
protected:
cocos2d::EventListenerTouchOneByOne* m_touchListener; //触屏事件监听器
ButtonTouchedCallback m_callback; //按钮回调函数
};
#endif // __POPUP_LAYER_H__
PopupLayer.cpp
#include "PopupLayer.h"
USING_NS_CC;
using namespace ui;
const int TAG_BUTTON = 1;
// on "init" you need to initialize your instance
bool PopupLayer::init()
{
if ( !Layer::init() )
{
return false;
}
m_callback = nullptr;
//获取游戏区域
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
//添加透明遮罩
auto mask = LayerColor::create(Color4B(0, 0, 0, 128), visibleSize.width, visibleSize.height);
this->addChild(mask);
//由于PopupLayer将触摸事件吞噬了,导致在判断点击事件的时候
//使用了触摸点坐标是否在按钮是区域内的方式,这样Button的
//setBright方法会使得点击按钮的时候显示Disable状态的图片,
//因此将按钮的点击和禁用图片设置为一样,来解决这个问题。
auto button = Button::create("test.png", "test_effect.png", "test_effect.png");
button->setScale9Enabled(true);
button->setTitleText("test button");
button->setTitleFontSize(40);
button->setContentSize(Size(visibleSize.width / 2, visibleSize.width / 4));
button->setPosition(Vec2(origin.x + visibleSize.width / 2,
origin.y + visibleSize.height / 2));
button->addTouchEventListener(CC_CALLBACK_2(PopupLayer::buttonCallback, this));
this->addChild(button, 0, TAG_BUTTON);
//触摸屏事件监听
m_touchListener = EventListenerTouchOneByOne::create();
m_touchListener->onTouchBegan = CC_CALLBACK_2(PopupLayer::onTouchBegan, this);
m_touchListener->onTouchMoved = CC_CALLBACK_2(PopupLayer::onTouchMoved, this);
m_touchListener->onTouchEnded = CC_CALLBACK_2(PopupLayer::onTouchEnded, this);
m_touchListener->onTouchCancelled = CC_CALLBACK_2(PopupLayer::onTouchCancelled, this);
m_touchListener->setSwallowTouches(true);
this->getEventDispatcher()->addEventListenerWithFixedPriority(m_touchListener, -128);
return true;
}
void PopupLayer::SetCallBackFunc(ButtonTouchedCallback callfunc)
{
this->m_callback = callfunc;
}
//销毁layer并调用回调函数
void PopupLayer::DestroySelf(cocos2d::Ref* sender, ButtonResult result)
{
this->getEventDispatcher()->removeEventListener(m_touchListener);
m_callback(sender, result);
this->removeFromParentAndCleanup(true);
}
// 触摸开始事件
bool PopupLayer::onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *unused_event)
{
auto button = (Button*)this->getChildByTag(TAG_BUTTON);
if (button != nullptr)
{
const Size& size = button->getContentSize();
const Vec2& pos = button->getPosition();
Rect rect = Rect(pos.x - size.width / 2, pos.y - size.height / 2, size.width, size.height);
auto touchLocation = touch->getLocation();
if (rect.containsPoint(touchLocation))
{
button->setBright(false);
button->onTouchBegan(touch, unused_event);
}
}
return true;
}
// 触摸滑动
void PopupLayer::onTouchMoved(cocos2d::Touch *touch, cocos2d::Event *unused_event)
{
auto button = (Button*)this->getChildByTag(TAG_BUTTON);
if (button != nullptr)
{
const Size& size = button->getContentSize();
const Vec2& pos = button->getPosition();
Rect rect = Rect(pos.x - size.width / 2, pos.y - size.height / 2, size.width, size.height);
auto touchLocation = touch->getLocation();
if (rect.containsPoint(touchLocation))
{
button->onTouchMoved(touch, unused_event);
}
else
{
button->setBright(true);
}
}
}
// 触摸结束事件
void PopupLayer::onTouchEnded(cocos2d::Touch *touch, cocos2d::Event *unused_event)
{
auto button = (Button*)this->getChildByTag(TAG_BUTTON);
if (button != nullptr)
{
const Size& size = button->getContentSize();
const Vec2& pos = button->getPosition();
Rect rect = Rect(pos.x - size.width / 2, pos.y - size.height / 2, size.width, size.height);
auto touchLocation = touch->getLocation();
button->setBright(true);
if (rect.containsPoint(touchLocation))
{
button->onTouchEnded(touch, unused_event);
}
}
}
// 触摸取消事件
void PopupLayer::onTouchCancelled(cocos2d::Touch *touch, cocos2d::Event *unused_event)
{
auto button = (Button*)this->getChildByTag(TAG_BUTTON);
if (button != nullptr)
{
const Size& size = button->getContentSize();
const Vec2& pos = button->getPosition();
Rect rect = Rect(pos.x - size.width / 2, pos.y - size.height / 2, size.width, size.height);
auto touchLocation = touch->getLocation();
button->setBright(true);
if (rect.containsPoint(touchLocation))
{
button->onTouchCancelled(touch, unused_event);
}
}
}
void PopupLayer::buttonCallback(cocos2d::Ref* sender, cocos2d::ui::Widget::TouchEventType event)
{
if (Widget::TouchEventType::CANCELED == event)
{
auto button = (Button*)sender;
if (button != nullptr)
{
if (TAG_BUTTON == button->getTag())
{
DestroySelf(sender, ButtonResult::ButtonResult_OK);
}
}
}
}
HelloWorldScene.h
#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include "cocos2d.h"
#include "PopupLayer.h"
class HelloWorld : public cocos2d::Scene
{
public:
static cocos2d::Scene* createScene();
virtual bool init();
// a selector callback
void menuCloseCallback(cocos2d::Ref* pSender);
// implement the "static create()" method manually
CREATE_FUNC(HelloWorld);
public:
//弹出框按钮事件
void buttonPopupCallback(cocos2d::Ref* sender, ButtonResult result);
};
#endif // __HELLOWORLD_SCENE_H__
HelloWorldScene.cpp
#include "HelloWorldScene.h"
USING_NS_CC;
Scene* HelloWorld::createScene()
{
return HelloWorld::create();
}
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
//
// 1. super init first
if ( !Scene::init() )
{
return false;
}
auto visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
/
// 2. add a menu item with "X" image, which is clicked to quit the program
// you may modify it.
// add a "close" icon to exit the progress. it's an autorelease object
auto closeItem = MenuItemImage::create(
"CloseNormal.png",
"CloseSelected.png",
CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));
closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width/2 ,
origin.y + closeItem->getContentSize().height/2));
// create menu, it's an autorelease object
auto menu = Menu::create(closeItem, NULL);
menu->setPosition(Vec2::ZERO);
this->addChild(menu, 1);
/
// 3. add your codes below...
// add a label shows "Hello World"
// create and initialize a label
auto label = Label::createWithTTF("Hello World", "fonts/Marker Felt.ttf", 24);
// position the label on the center of the screen
label->setPosition(Vec2(origin.x + visibleSize.width/2,
origin.y + visibleSize.height - label->getContentSize().height));
// add the label as a child to this layer
this->addChild(label, 1);
// add "HelloWorld" splash screen"
auto sprite = Sprite::create("HelloWorld.png");
// position the sprite on the center of the screen
sprite->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));
// add the sprite as a child to this layer
this->addChild(sprite, 0);
//添加弹出模态层
auto login = PopupLayer::create();
login->SetCallBackFunc(CC_CALLBACK_2(HelloWorld::buttonPopupCallback, this));
this->addChild(login, 10);
return true;
}
void HelloWorld::menuCloseCallback(Ref* pSender)
{
//Close the cocos2d-x game scene and quit the application
Director::getInstance()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
/*To navigate back to native iOS screen(if present) without quitting the application ,do not use Director::getInstance()->end() and exit(0) as given above,instead trigger a custom event created in RootViewController.mm as below*/
//EventCustom customEndEvent("game_scene_close_event");
//_eventDispatcher->dispatchEvent(&customEndEvent);
}
void HelloWorld::buttonPopupCallback(cocos2d::Ref* sender, ButtonResult result)
{
switch (result)
{
case ButtonResult::ButtonResult_OK:
Director::getInstance()->end();
break;
default:
break;
}
}