EventListenerTouchOneByOne::create() 单点触摸

void HelloWorld::onEnter()
{
	Layer::onEnter();
	log("HelloWorld onEnter");

	// 创建一个事件监听器 OneByOne 为单点触摸
	auto listener = EventListenerTouchOneByOne::create();
	// 设置是否吞没事件,在 onTouchBegan 方法返回 true 时吞没
	listener->setSwallowTouches(true);
	// onTouchBegan 事件回调函数
	listener->onTouchBegan = CC_CALLBACK_2(HelloWorld::touchBegan, this);
	// onTouchMoved 事件回调函数
	listener->onTouchMoved =  CC_CALLBACK_2(HelloWorld::touchMoved, this);
	// onTouchEnded 事件回调函数
	listener->onTouchEnded =  CC_CALLBACK_2(HelloWorld::touchEnded, this);

	// 注册监听器
	EventDispatcher* eventDispatcher = Director::getInstance()->getEventDispatcher();
	eventDispatcher->addEventListenerWithSceneGraphPriority(listener, getChildByTag(kBoxA_Tag));
	eventDispatcher->addEventListenerWithSceneGraphPriority(listener->clone(), getChildByTag(kBoxB_Tag));
	eventDispatcher->addEventListenerWithSceneGraphPriority(listener->clone(), getChildByTag(kBoxC_Tag));

}

bool HelloWorld::touchBegan(Touch* touch, Event* event)
{
	// 获取事件所绑定的 target 
	auto target = static_cast<Sprite*>(event->getCurrentTarget());

	// 获取当前点击点所在相对按钮的位置坐标
	Vec2 locationInNode = target->convertToNodeSpace(touch->getLocation());
	Size s = target->getContentSize();
	Rect rect = Rect(0, 0, s.width, s.height);

	// 点击范围判断检测
	if (rect.containsPoint(locationInNode))
	{
		log("sprite x = %f, y = %f ", locationInNode.x, locationInNode.y);
		log("sprite tag = %d", target->getTag());
		target->runAction(ScaleBy::create(0.06f, 1.06f)); 
		return true;

	}
	return false;
}

void HelloWorld::touchMoved(Touch *touch, Event *event)
{
	log("onTouchMoved");
	auto target = static_cast<Sprite*>(event->getCurrentTarget());
	// 移动当前按钮精灵的坐标位置
	target->setPosition(target->getPosition() + touch->getDelta());
}

void HelloWorld::touchEnded(Touch *touch, Event *event)
{
	log("onTouchEnded");
	auto target = static_cast<Sprite*>(event->getCurrentTarget());
	log("sprite onTouchesEnded.. ");

	Vec2 locationInNode = target->convertToNodeSpace(touch->getLocation());
	Size s = target->getContentSize();
	Rect rect = Rect(0, 0, s.width, s.height);
	// 点击范围判断检测
	if (rect.containsPoint(locationInNode))
	{
		log("sprite x = %f, y = %f ", locationInNode.x, locationInNode.y);
		log("sprite tag = %d", target->getTag());
		target->runAction(ScaleTo::create(0.06f, 1.0f)); 
	}
}

void HelloWorld::onExit()
{
	Layer::onExit();
	log("HelloWorld onExit");
	Director::getInstance()->getEventDispatcher()->removeAllEventListeners();
}

posted @ 2015-09-30 02:18  Anzhongliu  阅读(1345)  评论(0编辑  收藏  举报