3
當點擊菜單項時,有沒有辦法在Cocos2d中獲取菜單按鈕的位置?單擊菜單項時獲取菜單項的位置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");
}
基本上會發生什麼上面 - 我創建了一個菜單,然後我調用一個函數它創建菜單項,一旦這些菜單項被創建,它們就被添加到菜單中。每個菜單項都有自己的目標,選擇器是someSelector功能,我想將參數傳遞給(菜單按鈕位置)。
我想在這裏做的是,
當我運行在模擬器我希望能夠得到按下菜單按鈕的位置的程序。
謝謝,期待您的迴音。
我想我找到了解決自己的問題:
-(void)someSelector:(id)selector
已變成
-(void)someSelector:(CCMenuItem *) item
,然後你可以這樣做:
NSLog(@"Grid is pressed %f %f", item.position.x, item.position.y);
,瞧! :)
這是偉大的hspain!非常感謝。你能解釋一下嗎?所以我認爲選擇器是某種分配給已按下的菜單項的ID。是對的嗎? – Eugene
它實際上應該說「發件人」,我已經更新了我的回覆。 sender參數是對已被按下的菜單項的引用。然後,您可以將其轉換爲CCMenuItem,因爲您知道調用該事件的是什麼。 – hspain