1. 程式人生 > >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();
	}