dunvi
dunvi

Reputation: 53

Stopping touch propagation in cocos2d

We are working on a game in cocos2d in which there is a possibility of getting a trivia question. The trivia question is implemented as a new, transparent CCLayer on top of the gameboard, which contains a CCMenu with all of the questions.

Our problem is that we can't seem to get the touches to stop propagating properly. When the trivia menu is up, players should not be able to click on the "roll dice" button on the board layer.

We have tried implementing this by calling dice.isTouchEnabled=NO; right before adding the trivia layer, but we can't figure out how to re-enable the dice button.

We also tried changing ccTouchBegan from NO to YES to always consume all of the touches, but then it stops responding to our menu. It seems that this should be the right way to do it, but why did the menu stop responding then?

Our professor suggested implementing a callback function, which we of course can do, but it seems like it should be easier than that.

Does anyone have any suggestions?

Upvotes: 0

Views: 319

Answers (1)

jyek
jyek

Reputation: 1091

I understand that there are two ways to do this.

Method 1 (method that I am using)

  1. Before trivia question pops up, use the function below to disable menus on the Underlying Scene node. The method is a recursive method so it disables all menus on the node's children too.

  2. When the trivia question is dismissed, send an NSNotification which will be received by the Underlying Scene node and will re-enable menus on the node and its children. You can use the block method of NSNotification to shorten your code.

Docs on addObserverForName:object:queue:usingBlock:

(void) MenuStatus:(BOOL)_enable Node:(id)_node {

    for (id result in ((CCNode *)_node).children) {
        if ([result isKindOfClass:[CCMenu class]]) {
            for (id result1 in ((CCMenu *)result).children) {
                if ([result1 isKindOfClass:[CCMenuItem class]]) {
                    ((CCMenuItem *)result1).isEnabled = _enable;
                }
            }
        }
        else
            [self MenuStatus:_enable Node:result];
    }
}

Method 2

Create an invisible layer that will swallow all touches below the Trivia Question layer. Here is a class you can try: https://gist.github.com/christophercotton/1563708

Upvotes: 2

Related Questions