单击菜单项时获取菜单项位置Cocos2D(将它们传递给函数)

时间:2012-05-08 21:56:32

标签: iphone objective-c ios cocos2d-iphone

点击它后,有没有办法在Cocos2d中获取菜单按钮的位置?

所以我有一个菜单:

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");
}

基本上上面发生的是 - 我创建一个菜单,然后我调用一个创建菜单项的功能,一旦创建了这些菜单项,它们就被添加到菜单中。每个菜单项都有一个self目标,而selector是someSelector函数,我想将参数传递给(菜单按钮位置)。

我想在这里做的是,

当我在模拟器中运行程序时,我希望能够按下菜单按钮的位置。

谢谢,期待收到您的回复。

我想我找到了解决自己问题的方法:

-(void)someSelector:(id)selector

必须改为

-(void)someSelector:(CCMenuItem *) item

然后你可以这样做:

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

1 个答案:

答案 0 :(得分:4)

在您的处理程序中,您可以将发件人强制转换为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;
}