参考文章:
star特530的CSDN博客:http://blog.csdn.net/star530/article/details/18325493
https://github.com/chukong/cocos-docs/blob/master/manual/framework/native/v3/event-dispatcher/zh.md
Size visibleSize = Director::getInstance()->getVisibleSize();
Point origin = Director::getInstance()->getVisibleOrigin();
auto sprite = Sprite::create("CloseNormal.png");
sprite->setPosition(origin + Point(visibleSize.width / 2, visibleSize.height / 2) + Point(-80, 80));
addChild(sprite, 1);
auto sprite2 = Sprite::create("CloseNormal.png");
sprite2->setPosition(100, 100);
addChild(sprite2, 1);
auto listener1 = EventListenerTouchOneByOne::create(); //创建一个触摸监听
listener1->setSwallowTouches(false);
//用lambda表达式
listener1->onTouchBegan = [](Touch *touch, Event *event){
auto target = static_cast<Sprite*>(event->getCurrentTarget()); //获取当前触摸的目标
auto locationInNode = target->convertToNodeSpace(touch->getLocation()); //target相对于触摸点的坐标位置
auto s = target->getContentSize(); //目标的矩形大小,逻辑尺寸,不是像素
auto rect = Rect(0, 0, s.width, s.height);
//判断触摸点是否在目标的范围内
if (rect.containsPoint(locationInNode)){
return true;
}
return false;
//要判断触摸点是否在目标的范围内,可以用另外一种方法。程序在上面部分就已经返回,这部分不会执行
//getBoundingBox()
if (event->getCurrentTarget()->getBoundingBox().containsPoint(touch->getLocation()))
return true;
return false;
};
可以用cocos2d-x的回调函数方式
//listener1->onTouchBegan = CC_CALLBACK_2(HelloWorldScene::onTouchBegan, this);
或者用std::bind
//listener1->onTouchBegan = std::bind(&HelloWorldScene::onTouchBegan, this, placeholders::_1, placeholders::_2);
再或者std::function
//std::function<bool(Touch*, Event*)> func = [](Touch *touch, Event *event){
// //省略代码
//};
//listener1->onTouchBegan = func;
listener1->onTouchMoved = [](Touch *touch, Event *event){
auto target = static_cast<Sprite*>(event->getCurrentTarget());
target->setPosition(target->getPosition() + touch->getDelta());
};
//将触摸监听添加到_eventDispatcher,sprite这个参数应该是表示event->getCurrentTarget()这个目标
//假设有另外一个sprite2,如果这里用的是sprite2,那么移动的就是sprite2
//如果同时有sprite和sprite2,这里用的是this,那么移动的是整个layer,也就是说sprite和sprite2是同时移动的
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener1, sprite);
//有多个sprite想都可以移动, 用clone()
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener1->clone(), sprite2);