Getting the location of a menu item when you click a Cocos2D menu item (passing them to a function)

Is there a way to get the location of the menu button in Cocos2d when I clicked it?

So I have a menu:

HelloWorld.h

//creating a menu
CCMenu *menu;

HelloWorld.m

// initializing the menu and its position
menu = [CCMenu menuWithItems:nil];
menu.position = ccp(0,0);

// set cells in placing grid
[self setItem];
[self addChild:menu];

- (void)setItem
{
  //this method is a loop that creates menu items
  //but i've simplified it for this example, but please keep in mind that there are lots 
  //of menu items and tagging them could be troublesome

  for (int i = 1; i <= 13; i++) {
      for (int j = 1; j <= 8; j++) {

        // this creates a menu item called grid
        CCMenuItem grid = [CCMenuItemSprite 
          itemWithNormalSprite:[CCSprite spriteWithSpriteFrameName:@"menuItem.png"]
          selectedSprite:[CCSprite spriteWithSpriteFrameName:@"selected.png"] 
          target:self 
          // when button is pressed go to someSelector function
          selector:@selector(someSelector:)];

          //coordinates
          float x = (j+0.55) * grid.contentSize.width;
          float y = (i-0.5) * grid.contentSize.height;

          //passing the coordinates
          grid.position = ccp(x, y);

          //add grid to the menu
          [menu addChild:grid];

          //loop unless finished
       }
  }

}

-(void)someSelector:(id)selector
{
   //i know when the button is pressed but is there any way 
   //to pass selected menu coordinates to this function?
   NSLog(@"Grid is pressed");
}

Basically, what happens above, I create a menu, then I call a function that creates menu items, after creating these menu items they are added to the menu. Each menu item has a purpose of self and selector - someSelector function, which I want to pass to the parameters (the location of the menu button).

What I want to do here

When I run the program in the simulator, I want to be able to find the location of the menu button.

Thanks, expecting to hear from you.

I think I found a solution to my question:

-(void)someSelector:(id)selector

need to change to

-(void)someSelector:(CCMenuItem *) item

and then you can do this:

NSLog(@"Grid is pressed %f %f", item.position.x, item.position.y);

and voila! :)

+3
1

CCMenuItem :

-(void)someSelector:(id)sender
{
   //i know when the button is pressed but is there any way 
   //to pass selected menu coordinates to this function?
   NSLog(@"Grid is pressed");
   CCMenuItem* menuItem = (CCMenuItem*)sender;
   float x = menuItem.position.x;
   float y = menuItem.position.y;
}
+4

All Articles