objective-ccocos2d-iphoneccmenuitem

How to deal with CCMenuItem in Cocos2d


I'm new with Cocos2d and try port game from normal Cocoa Touch to Cocos2d.

I created some button by custom method:

+ (CCMenuItem *)createMenuItemImageWithNormalImage:(NSString *)normalImage selectedImage:(NSString *)selectedImage tag:(int)tag target:(id)target selector:(SEL)selector position:(CGPoint)position {

    CCMenuItem *item = [CCMenuItemImage itemWithNormalImage:normalImage selectedImage:selectedImage];
    item.tag = tag;
    [item setTarget:target selector:selector];
    item.position = [TSCCTransform transformPositionFromCocoaTouchToCocos2d:CGPointMake(position.x, position.y)];

    return item;
}

Button:

    [self addChild:[TSCCLayer createMenuItemImageWithNormalImage:@"btn-mouse-dec.png" selectedImage:@"btn-mouse-dec.png" tag:0 target:self selector:@selector(changeNumberOfPlayers:) position:ccp([TSCCTransform winSizeWidth] - 140, 146)]];

But nothing happened when i click on it. Where's the problem? How do it correctly?


Solution

  • You don't have to add a menu item to it, but a menu.

    Add that CCMenuItem to a CCMenu, and then add the menu as child of the layer:

    CCMenuItem* item=[TSCCLayer createMenuItemImageWithNormalImage:@"btn-mouse-dec.png" selectedImage:@"btn-mouse-dec.png" tag:0 target:self selector:@selector(changeNumberOfPlayers:) position:ccp([TSCCTransform winSizeWidth] - 140, 146)]
    CCMenu* menu= [CCMenu menuWithItems: item, nil];  // item becomes child of menu
    [self addChild: menu];