cocos2dx中精灵点击事件处理的两种方式——Sprite和ImageView

前端之家收集整理的这篇文章主要介绍了cocos2dx中精灵点击事件处理的两种方式——Sprite和ImageView前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
1. ImageView 的方式:封装的Widget组件ImageVIew实现了类似按钮的监听事件,所以处理起来很方便直接
ImageView*		_pPokerImageView;

_pPokerImageView = ImageView::create(tmpStr);
		_pPokerImageView->setAnchorPoint(Vec2(0,0));
		_pPokerImageView->setTouchEnabled(true);
		addChild(_pPokerImageView);
		_pPokerImageView->addTouchEventListener([this](Ref* pSender,Widget::TouchEventType type)
		{
			if (type == Widget::TouchEventType::ENDED)
			{
				PokerEventStatus tmpStatus = (getStatusValue() == SelectedStatus) ? NormalStatus : SelectedStatus;
				updateSelectedSigned(tmpStatus);

				if (getStatusValue() == SelectedStatus)
				{
					updateSelectedSigned(SelectedStatus);
				}
				else
				{
					updateSelectedSigned(NormalStatus);
				}
			}
2.Sprite的方式:需要手动实现监听事件代码,而且需要根据坐标,size去做精灵点击区域判断,写起来稍微复杂点,不过条条道路通罗马,多点方式,多种选择
</pre><pre name="code" class="cpp">EventListenerTouchOneByOne* _spriteListener;
Sprite*		_pPokerSprite;
/* 添加事件监听 */
			_spriteListener = EventListenerTouchOneByOne::create();
			
			_spriteListener->onTouchBegan = [this](Touch* touch,Event* event) -> bool {

				/* 获取事件所绑定的 target */
				auto target = event->getCurrentTarget();

				/* 获取当前点击点所在相对按钮的位置坐标 */
				Vec2 locationInNode = target->convertToNodeSpace(touch->getLocation());
				Size targetSize = target->getContentSize();
				Rect rect = Rect(_pPokerSprite->getPositionX(),_pPokerSprite->getPositionY(),COCOSNODE_WIDTH(_pPokerSprite),COCOSNODE_HEIGHT(_pPokerSprite));

				bool isClicked = rect.containsPoint(locationInNode);
				/* 点击范围判断 */
				if (isClicked)
				{
					PokerEventStatus tmpStatus = (getStatusValue() == SelectedStatus) ? NormalStatus : SelectedStatus;
					updateSelectedSigned(tmpStatus);

					if (getStatusValue() == SelectedStatus)
					{
						updateSelectedSigned(SelectedStatus);
					}
					else
					{
						updateSelectedSigned(NormalStatus);
					}
				}

				/* 此处一定要动态设置事件吞噬,否则层只会响应最后一张加入精灵的事件 */
				_spriteListener->setSwallowTouches(isClicked);

				return isClicked;
			};


在init时同时初始化精灵,加入层
 
 
_pPokerSprite = Sprite::createWithTexture(pChessTexture,tmpRect);
		_pPokerSprite->setAnchorPoint(Vec2(0,0));
		addChild(_pPokerSprite);

然后在onEnter里加入监听:
void TBBullFightPoker::onEnter(void)
	{
		Node::onEnter();


		do 
		{
			CC_BREAK_IF(!_pPokerSprite);


			_eventDispatcher->addEventListenerWithSceneGraPHPriority(_spriteListener,_pPokerSprite);


		} while (0);
	}
同样在onExit里删除监听:
void TBBullFightPoker::onExit(void)
	{
		_eventDispatcher->removeEventListener(_spriteListener);


		Node::onExit();
	}
原文链接:https://www.f2er.com/cocos2dx/339848.html

猜你在找的Cocos2d-x相关文章