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


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值