cocos2d-x 3.0 事件处理

參考文章:

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);


原文地址:https://www.cnblogs.com/hrhguanli/p/3775890.html