1、事件处理方法
下面为普通的点击事件监听器(下面简称EventListener)注册部分;注册EventListener需要实现onTouchBegan方法,可以实现onTouchEnded、onTouchCancelled方法,当然如果你想监听触控(鼠标)移动(拖动)监听器需要实现onTouchMoved方法,这里使用Lambda方式简单实现了onTouchBegin方法;
auto event =EventListenerTouchOneByOne::create();
event->onTouchBegan= [sprite](Touch *touch, Event *event){
if(sprite->getBoundingBox().containsPoint(touch->getLocation())){
……
return true; //此时的返回值很关键;true会继续调用下面的onTouchEnded方法,false不会调用onTouchEnded方法
}
return false;
};
event->onTouchEnded= [this](Touch *touch, Event *event){
……
};
Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(event,sprite);//注册EventListener
在Cocos2dx事件处理系统中并不会区分事件是哪个Node发出的。不管你点击屏幕什么位置(当然点击黑边位置只会打印错误信息),Cocos2dx会将所有的注册EventListener处理方法都会执行一遍;故在事件处理程序中需要添加
if(sprite->getBoundingBox().containsPoint(touch->getLocation()))
来判断点击是否为该注册EventListener;
2、EventListener注册方法
在上述实例中时候用addEventListenerWithSceneGraphPriority方法注册的EventListener,在Cocos2dx中还支持其他几种EventListener的注册方式