cocos2d layer not responding to touches after a menu layer is popped
I'm making a game using cocos2d for iOS. When the main gameplay layer constructor is called, it registers to receive touches with 开发者_开发百科the following call:
[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self
priority:0
swallowsTouches:YES];
That works fine. When the user pauses the game, I push a pause menu layer onto the CCDirector
. The pause menu layer registers to receive touches in the same way as above. The first option in that menu is to resume the game (i.e. to pop the menu layer and go back to the game in progress). However, when this happens, the gameplay layer no longer responds to touches.
What is the best way to handle this? I guess I could register the gameplay layer as the targeted delegate in every call to Update
, but that seems kind of ridiculous. Is there a way to reassign the delegate within the pause menu before closing it? Is there an accepted way of doing this?
As it turns out, there's a known issue with CCMenu
stealing the focus from the underlying CCLayer
object when returning from a popped scene. The accepted way around this, as I have found on the cocos2d forums, is to, rather than creating a new scene, overlay a transparent layer (to dim the existing scene) with a CCMenu
in it. When you are done with this CCMenu
, you simply remove it from the scene.
Here's my specific implementation:
-(void)pauseMenuButtonPressed
{
if(!paused)
{
paused = TRUE;
[[CCDirector sharedDirector] pause];
CGSize s = [[CCDirector sharedDirector] winSize];
pauseLayer = [CCColorLayer layerWithColor: ccc4(150, 150, 150, 125) width: s.width height: s.height];
pauseLayer.position = CGPointZero;
[self addChild: pauseLayer z:8];
CCMenuItem *pauseMenuItemResume =[CCMenuItemImage itemFromNormalImage:@"menuItemResumeSmall.png"
selectedImage: @"menuItemResumeSmallSelected.png"
target:self
selector:@selector(pauseMenuResumeSelected)];
CCMenuItem *pauseMenuItemMainMenu =[CCMenuItemImage itemFromNormalImage:@"menuItemMainMenuSmall.png"
selectedImage: @"menuItemMainMenuSmallSelected.png"
target:self
selector:@selector(pauseMenuExitToMainMenuSelected)];
// Create the pause menu and add the menu items to it
pauseMenu = [CCMenu menuWithItems:pauseMenuItemResume, pauseMenuItemMainMenu, nil];
// Arrange the menu items vertically
[pauseMenu alignItemsVertically];
// add the menu to the scene
[self addChild:pauseMenu z:10];
[hudButtons setIsTouchEnabled:NO];
}
}
-(void)pauseMenuResumeSelected
{
[self removeChild:pauseMenu cleanup:YES];
[self removeChild:pauseLayer cleanup:YES];
[hudButtons setIsTouchEnabled:YES];
[[CCDirector sharedDirector] resume];
paused = FALSE;
}
Doesn't it work if you release your pause menu object? Or you could just move the pause layer outside of the screen when it's not active. Set it's x,y to -1000 or something.
精彩评论