单点触摸:EventListenerTouchOneByOne
// Make sprite1 touchable
auto containerForSprite1 = Node::create();
auto sprite1 = Sprite::create("Images/CyanSquare.png");
sprite1->setPosition(origin+Vec2(size.width/2,size.height/2) + Vec2(-80,80));
containerForSprite1->addChild(sprite1);
addChild(containerForSprite1,10);
auto sprite2 = Sprite::create("Images/magentaSquare.png");
sprite2->setPosition(origin+Vec2(size.width/2,size.height/2));
addChild(sprite2,20);
auto sprite3 = Sprite::create("Images/YellowSquare.png");
sprite3->setPosition(Vec2(0,0));
sprite2->addChild(sprite3,1);
创建监听器
auto listener1 = EventListenerTouchOneByOne::create();
listener1->setSwallowtouches(true);
listener1->onTouchBegan = [](Touch* touch,Event* event){ C++11最新的功能std::function
auto target = static_cast<Sprite*>(event->getCurrentTarget());获得订阅者本身
Vec2 locationInNode = target->convertToNodeSpace(touch->getLocation());
Size s = target->getContentSize();
Rect rect = Rect(0,s.width,s.height);
if (rect.containsPoint(locationInNode))
{
log("sprite began... x = %f,y = %f",locationInNode.x,locationInNode.y);
target->setopacity(180);
return true;
}
return false;
};
listener1->onTouchMoved = [](Touch* touch,Event* event){
auto target = static_cast<Sprite*>(event->getCurrentTarget());
target->setPosition(target->getPosition() + touch->getDelta());//getLocation() - getPrevIoUsLocation()
};
listener1->onTouchEnded = [=](Touch* touch,Event* event){
auto target = static_cast<Sprite*>(event->getCurrentTarget());
log("sprite ontouchesEnded.. ");
target->setopacity(255);
if (target == sprite2)
{
containerForSprite1->setLocalZOrder(100);
}
else if(target == sprite1)
{
containerForSprite1->setLocalZOrder(0);
}
};
auto_eventdispatcher=Director::getInstence()->getdispatcher();
注册监听器:
_eventdispatcher->addEventListenerWithSceneGraPHPriority(listener1,sprite1);
_eventdispatcher->addEventListenerWithSceneGraPHPriority(listener1->clone(),sprite2);克隆监听器
_eventdispatcher->addEventListenerWithSceneGraPHPriority(listener1->clone(),sprite3);
清除监听:
auto removeAllTouchItem = MenuItemFont::create("Remove All Touch Listeners",[this](Ref* sender){
auto senderItem = static_cast<MenuItemFont*>(sender);
senderItem->setString("Only Next item Could be clicked");
_eventdispatcher->removeEventListenersForType(EventListener::Type::TOUCH_ONE_BY_ONE);
自定义事件:
auto listener = EventListenerCustom::create("game_custom_event1", [=](EventCustom* event){
std::string str("Custom event 1 received,");
char* buf = static_cast<char*>(event->getUserData());
str += buf;
str += " times";
statusLabel->setString(str.c_str());
});
_eventdispatcher->addEventListenerWithFixedPriority(_listener,1);
auto sendItem = MenuItemFont::create("Send Custom Event 1",[=](Ref* sender){
static int count = 0;
++count;
char* buf = new char[10];
sprintf(buf,"%d",count);
EventCustom event("game_custom_event1");
event.setUserData(buf);
_eventdispatcher->dispatchEvent(&event);
CC_SAFE_DELETE_ARRAY(buf);
});