最近在用cocos2d-x写游戏,写游戏当然少不了要用触屏处理事件啦~本来是一件很容易的事情,可是可是,坑爹的东西却让我纠结了一个晚上啊啊啊啊!!!!!
网上一搜一大堆这样的博客文章,有详细的,有简略的,于是一步步地按照步骤来,一下子就code出来了,可是一运行,鼠标一点,啊,怎么没反应,难道写错了?不会吧
好吧,进入调试模式,在触屏事件处理函数中设置断点,调试,怎么不会中断啊,这就奇了怪了,它就压根没有进入到处理函数中。怎么回事呢?网上又一搜,搜了好久好久,没有找到答案,好吧,还是自己来吧。
于是,我重新写了一个TestClick来测试一下到底是怎么回事,处理函数如下:
void TestClick::ccTouchesEnded(CCSet* pTouches, CCEvent *pEvent)
{
CCSprite *sprite = CCSprite::spriteWithFile("CloseSelected.png");
sprite->setPosition(ccp(100, 100));
this->addChild(sprite, 1);
sprite->setPosition(ccp(100, 200));
}
如果正确的话, 应该会出现图片的。。。。
那究竟是什么原因呢,下面来看下init()函数
bool TestClick::init()
{
bool bRet = false;
do
{
//
// super init first
//
this->setIsTouchEnabled(true);
CC_BREAK_IF(! CCLayer::init());
//
// add your codes below...
//
// Create a "close" menu item with close icon, it's an auto release object.
CCMenuItemImage *pCloseItem = CCMenuItemImage::itemFromNormalImage(
"CloseNormal.png",
"CloseSelected.png",
this,
menu_selector(HelloWorld::menuCloseCallback));
CC_BREAK_IF(! pCloseItem);
// Place the menu item bottom-right conner.
pCloseItem->setPosition(ccp(CCDirector::sharedDirector()->getWinSize().width - 20, 20));
// Create a menu with the "close" menu item, it's an auto release object.
CCMenu* pMenu = CCMenu::menuWithItems(pCloseItem, NULL);
pMenu->setPosition(CCPointZero);
CC_BREAK_IF(! pMenu);
// Add the menu to HelloWorld layer as a child layer.
this->addChild(pMenu, 1);
// Create a label and initialize with string "Hello World".
CCLabelTTF* pLabel = CCLabelTTF::labelWithString("Hello World", "Thonburi", 64);
CC_BREAK_IF(! pLabel);
// Get window size and place the label upper.
CCSize size = CCDirector::sharedDirector()->getWinSize();
pLabel->setPosition(ccp(size.width / 2, size.height - 20));
// Add the label to HelloWorld layer as a child layer.
this->addChild(pLabel, 1);
// 3. Add add a splash screen, show the cocos2d splash image.
CCSprite* pSprite = CCSprite::spriteWithFile("HelloWorld.png");
CC_BREAK_IF(! pSprite);
// Place the sprite on the center of the screen
pSprite->setPosition(ccp(size.width/2, size.height/2));
// Add the sprite to HelloWorld layer as a child layer
this->addChild(pSprite, 0);
bRet = true;
} while (0);
return bRet;
}
很正常的代码,我只添加了一句this->setIsTouchEnable(true); 而已啊,其它的是创建的时候自动生成的啊,难道这一句出了问题,不会吧。。。。
于是继续探索,发现下一句是CCLayer::init()难道这里面有古怪?
好,那就去看看,源码如下:
bool CCLayer::init()
{
bool bRet = false;
do
{
CCDirector * pDirector;
CC_BREAK_IF(!(pDirector = CCDirector::sharedDirector()));
this->setContentSize(pDirector->getWinSize());
m_bIsTouchEnabled = false;
m_bIsAccelerometerEnabled = false;
// success
bRet = true;
} while(0);
return bRet;
}
好啦,找到问题的所在了,
m_bIsTouchEnabled = false;
这一句就是罪恶的根源啊啊啊啊,在初始化的时候,默认是将触屏disable的,所以所以所以
一定要在CCLayer::init()之后才调用setIsTouchEnabled(
true
);
改过来,瞬间可以了