2014-01-31 3 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

아니요, 모든 Sprite에 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- 인덱스와 스프라이트를 만지지 때문에 역순으로 반복합니다.

희망,이 도움.

+0

감사합니다. 권장되는 최적의 방법입니까? – user63898

+0

가장 깨끗하고 우아한 방법은 모르겠지만, 여러 번 나에게 효과적이며, 움직일 때 (실행중인 애니메이션에서) 스프라이트에 대한 터치를 처리 할 수 ​​있습니다. 나는 그것을 숨겨진 객체 게임에 사용했고 잘 동작합니다. –