-
CCTouchDelegate已经停用了
8 使用触摸事件移动 精灵
cocos2d-x 3.0 不再使用 TouchDelegate方式来将touch事件捆绑到sprite上。
新的方法是
auto listener = EventListenerTouchOneByOne::create();
listener->setSwallowTouches(true);
listener->onTouchBegan = CC_CALLBACK_2(CMyFirstScene::onTouchBegan, this);
listener->onTouchMoved = CC_CALLBACK_2(CMyFirstScene::onTouchMoved, this);
listener->onTouchEnded = CC_CALLBACK_2(CMyFirstScene::onTouchEnded, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
这段代码可以放在.cpp里面的 init里。
头文件增加:
Sprite *s;
// 初始化
bool onTouchBegan(Touch* touch, Event* event);
void onTouchMoved(Touch* touch, Event* event);
void onTouchEnded(Touch* touch, Event* event);
void selectSpriteForTouch(Point touchLocation);
s 为全局的精灵。
bool CMyFirstScene::onTouchBegan(Touch* touch, Event* event)
{
CCLOG("TouchBegan");
Point touchLocation = this->convertTouchToNodeSpace(touch);
this->selectSpriteForTouch(touchLocation);
return true;
}
void CMyFirstScene::onTouchMoved(Touch* touch, Event* event)
{
CCLOG("TouchMoved");
}
void CMyFirstScene::onTouchEnded(Touch* touch, Event* event)
{
CCLOG("TouchEnded");
}
void CMyFirstScene::selectSpriteForTouch(Point touchLocation)
{
if (s->getBoundingBox().containsPoint(touchLocation) )
{
Action* actionMove =
MoveTo::create( 2.0,
ccp(300, 200) );
s->runAction(actionMove);
}
}