2014-01-31 41 views
0

我想檢測哪個精靈被觸摸。 如果我這樣做:我是否需要爲每個我想檢測的精靈設置addEventListenerWithSceneGraphPriority?

auto listener = EventListenerTouchOneByOne::create(); 
listener->setSwallowTouches(true); 
listener->onTouchBegan = CC_CALLBACK_2(HelloWorld::onTouchBegan, this); 
listener->onTouchMoved = CC_CALLBACK_2(HelloWorld::onTouchMoved, this); 
listener->onTouchEnded = CC_CALLBACK_2(HelloWorld::onTouchEnded, this); 
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); 
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener->clone(), mySprite); 

,然後在我的觸摸方法我做的:

bool HelloWorld::onTouchBegan(Touch* touch, Event* event) 
auto spriteBlock = static_cast<Block*>(event->getCurrentTarget()); 

精靈檢測的罰款。

的問題是我有這樣的層20級的精靈,我需要能夠檢測到它們所有 做我需要設置

_eventDispatcher->addEventListenerWithSceneGraphPriority(listener->clone(), mySprite); 

每個精靈?

回答

2

不,你不需要爲所有精靈添加eventListener。

您需要一個事件偵聽器,用於精靈的父節點。

試試這個:

bool HelloWorld::onTouchBegan(Touch *touch, Event *event) { 
    Node *parentNode = event->getCurrentTarget(); 
    Vector<Node *> children = parentNode->getChildren(); 
    Point touchPosition = parentNode->convertTouchToNodeSpace(touch); 
    for (auto iter = children.rbegin(); iter != children.rend(); ++iter) { 
     Node *childNode = *iter; 
     if (childNode->getBoundingBox().containsPoint(touchPosition)) { 
      //childNode is the touched Node 
      //do the stuff here 
      return true; 
     } 
    } 
    return false; 
} 

這是相反的順序,因爲你會碰在地方最高的z-index精靈迭代(如果它們重疊)。

希望這個幫助。

+0

謝謝,這是推薦的最佳方式嗎? – user63898

+0

我不知道它是最乾淨和最優雅的方式,但它對我來說已經好幾次了,它可以在移動時(在運行中的動畫中)處理對精靈的觸摸。我用它在一個隱藏的對象遊戲中,它的工作正常。 –

相關問題