欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  数据库

coco2dx 3.0 EventDispatcher事件派发

程序员文章站 2022-04-27 23:03:02
...

在看3.0的TestCpp中的示例出现了,EventDispatcher的示例。 图片如下 添加了三张图片,但是每张点击到都会响应触摸事件,并且调整Z坐标。 按照示例的代码: Point origin = Director::getInstance()-getVisibleOrigin();Size size = Director::getInstance()

在看3.0的TestCpp中的示例出现了,EventDispatcher的示例。

图片如下

coco2dx 3.0 EventDispatcher事件派发

添加了三张图片,但是每张点击到都会响应触摸事件,并且调整Z坐标。

按照示例的代码:

	Point origin = Director::getInstance()->getVisibleOrigin();
	Size size = Director::getInstance()->getVisibleSize();

	//auto containerForSprite1 = Node::create();
	auto sprite1 = Sprite::create("SpriteTouchEvent/1.png");
	sprite1->setPosition(origin+Point(size.width/2, size.height/2) + Point(-80, 0));
	addChild(sprite1);
	//addChild(containerForSprite1, 10);

	auto sprite2 = Sprite::create("SpriteTouchEvent/2.png");
	sprite2->setPosition(origin+Point(size.width/2, size.height/2));
	addChild(sprite2, 20);

	auto sprite3 = Sprite::create("SpriteTouchEvent/3.png");
	sprite3->setPosition(origin+Point(size.width/2, size.height/2) + Point(80, 0));
	addChild(sprite3, 30);

	// Make sprite1 touchable
	auto listener1 = EventListenerTouchOneByOne::create();
	listener1->setSwallowTouches(true);

	listener1->onTouchBegan = [](Touch* touch, Event* event)
	{
		auto target = static_cast(event->getCurrentTarget());

		Point locationInNode = target->convertToNodeSpace(touch->getLocation());
		Size s = target->getContentSize();
		Rect rect = Rect(0, 0, s.width, s.height);

		if (rect.containsPoint(locationInNode))
		{
			//target->setOpacity(180);
			return true;
		}
		return false;
	};

	listener1->onTouchMoved = [](Touch* touch, Event* event)
	{
// 		auto target = static_cast(event->getCurrentTarget());
// 		target->setPosition(target->getPosition() + touch->getDelta());
	};

	listener1->onTouchEnded = [=](Touch* touch, Event* event)
	{
		auto target = static_cast(event->getCurrentTarget());
		log("sprite onTouchesEnded.. ");
		//target->setOpacity(255);
		if (target == sprite2)
		{
			sprite2->setLocalZOrder(100);
		}
		else
		{
			sprite2->setLocalZOrder(20);
		}
		if(target == sprite1)
		{
			sprite1->setLocalZOrder(100);
		}
		else
		{
			sprite1->setLocalZOrder(10);
		}
		if(target == sprite3)
		{
			sprite3->setLocalZOrder(100);
		}
		else
		{
			sprite3->setLocalZOrder(30);
		}
	};

 	_eventDispatcher->addEventListenerWithSceneGraphPriority(listener1, sprite1);
 	_eventDispatcher->addEventListenerWithSceneGraphPriority(listener1->clone(), sprite2);
	_eventDispatcher->addEventListenerWithSceneGraphPriority(listener1->clone(), sprite3);


代码修改了一点,值为了点击哪张图片,与此同时这个图片就会把Z坐标提升。

---------------------------------------我是在一步步的爬坑----------------------------------------