cocos2d-iphoneccmenuitem

CCMenu child of child selector not firing


I have a ccmenu with a ccmenuitemsprite in a ccmenuitemsprite which has the selector. I wish for the child of child to be a play button that fires a selector but its not firing.

CCMenu *menu [CCMenu menuWithItems: nil];
CCMenuItem *bg = [CCMenuItemSprite itemFromNormalSprite:[CCSprite spriteWithFile:@"sprite_sheet.png" rect:CGRectMake(0,50,100,100)] 
                                         selectedSprite:nil 
                                         disabledSprite:nil 
                                                 target:self 
                                               selector:nil];
CCMenuItem *playBtn = [CCMenuItemSprite itemFromNormalSprite:[CCSprite spriteWithFile:@"sprite_sheet.png" rect:CGRectMake(0,0,50,50)] 
                                              selectedSprite:[CCSprite spriteWithFile:@"sprite_sheet.png" rect:CGRectMake(50,0,50,50)] 
                                              disabledSprite:[CCSprite spriteWithFile:@"sprite_sheet.png" rect:CGRectMake(100,0,50,50)] 
                                                      target:self 
                                                    selector:@selector(onPlay:)];
[bg addChild:playBtn];
[menu addChild:bg];
[self addChild:menu];

Solution

  • If you want to pass the name of your images as arguments, please use the following code:

    CCMenuItem *playBtn = [CCMenuItemImage itemFromNormalImage:@"image.png"
                                                 selectedImage:@"image_selected.png"
                                                 disabledImage:@"image_disabled.png"
                                                        target:self
                                                      selector:@selector(onPlay:)];
    

    The constructor you are using is expecting a CCSprite, not an NSString.


    OK, after you edited the answer, I looked more closely, and you have the playBtn as a child of bg. You can't do that. Only the direct children of CCMenu are able to send callbacks:

    [menu addChild:playBtn];
    

    I would suggest you do this actually:

    CCMenuItem *playBtn = [CCMenuItemSprite itemFromNormalSprite:[CCSprite spriteWithFile:@"sprite_sheet.png" rect:CGRectMake(0,0,50,50)] 
                                                  selectedSprite:[CCSprite spriteWithFile:@"sprite_sheet.png" rect:CGRectMake(50,0,50,50)] 
                                                  disabledSprite:[CCSprite spriteWithFile:@"sprite_sheet.png" rect:CGRectMake(100,0,50,50)] 
                                                          target:self 
                                                        selector:@selector(onPlay:)];
    
    CCMenu* menu = [CCMenu menuWithItems:playBtn, nil];
    
    CCSprite* bg = [CCSprite spriteWithFile:@"sprite_sheet.png" rect:CGRectMake(0,50,100,100)];
    
    [self addChild:bg];
    [self addChild:menu];