看了看cocos2dx测试项目TouchesTest代码学到的一点东西吧。
在最开始设计自己的精灵类的时候,只是单单继承Sprite,在类里面然后直接添加事件监听的回调方法。
class ObjSth : public cocos2d::Sprite
{
public:
virtual void onEnter() override;
virtual void onExit() override;
public:
//添加事件监听的三个回调成员函数
bool onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* event);
void onTouchMoved(cocos2d::Touch* touch, cocos2d::Event* event);
void onTouchEnded(cocos2d::Touch* touch, cocos2d::Event* event);
};
在OnEnter()方法里实现事件的初始化。
void ObjSth::onEnter()
{
Sprite::onEnter();
// Register Touch Event
auto listener = EventListenerTouchOneByOne::create();
listener->setSwallowTouches(true);
listener->onTouchBegan = CC_CALLBACK_2(ObjSth::onTouchBegan, this);
listener->onTouchMoved = CC_CALLBACK_2(ObjSth::onTouchMoved, this);
listener->onTouchEnded = CC_CALLBACK_2(ObjSth::onTouchEnded, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
}
比如在屏幕中添加一个精灵,添加事件实现拖动。
在游戏场景中这么写:
bool Game Scene::init()
{
// 1. super init first
if ( !Layer::init() )
{
return false;
}
auto Obj = Sprite::create("001.png");
Obj->setPosition(Vec2(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y));
this->addChild(Ball, 0);
return true;
}
自己想当然写的,果然怎么运行也不成功。
设置断点压根不会运行到回调函数那里。
研究了下,做了如下改变。
类部分,添加了两个和初始化有关的方法:
class ObjSth : public cocos2d::Sprite
{
public:
virtual void onEnter() override;
virtual void onExit() override;
public:
//添加如下两个关于初始化成员函数
static ObjSth* createWithTexture(cocos2d::Texture2D* aTexture);
//添加事件监听的三个回调成员函数
bool onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* event);
void onTouchMoved(cocos2d::Touch* touch, cocos2d::Event* event);
void onTouchEnded(cocos2d::Touch* touch, cocos2d::Event* event);
};
实现如下:
ObjSth* ObjSth::createWithTexture(Texture2D* aTexture)
{
ObjSth* pObjSth = new (std::nothrow) ObjSth();
pObjSth->initWithTexture(aTexture);
pObjSth->autorelease();
return pObjSth;
}
在游戏场景中这么写:
bool Game Scene::init()
{
// 1. super init first
if ( !Layer::init() )
{
return false;
}
auto paddleTexture = Director::getInstance()->getTextureCache()->addImage("001.png");
auto Ball = ObjSth::createWithTexture(paddleTexture);
Ball->setPosition(Vec2(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y));
this->addChild(Ball, 0);
return true;
}
终于运行成功。