我想为我正在开发的游戏制作几百个关卡,所以显然我想使用for循环,而不是单独创建每个按钮。
我做这些都很好,但我目前使用的代码使得每个按钮的调用块是相同的。显然,如果我要让不同的关卡按钮进入不同的关卡,每个的调用块必须是不同的。
为了区分我在哪个级别,我称[[LevelManager sharedInstance] nextLevel]
为对应级别号的次数。我试图通过获取用户触摸按钮的触摸位置来改变这个数字,获取行/列数,然后运行上述代码若干次。然而,在触摸按钮后运行整个调用块之前,它没有更新触摸位置,这显然使我的代码不工作。
是否有一种方法可以手动更新触摸位置,在调用块结束之前?是否有一种方法可以以某种方式将每个按钮存储在数组中,并为每个按钮建立不同的调用块?我不确定解决我的问题的最佳方法是什么。谢谢,我的代码如下。
初始化时调用
for (int l = 0; l < NUMBER_OF_WORLDS; l++) {
for (int j = 0; j < 4; j++) {
for (int k = 0; k < 5; k++) {
NSString *tempTitle = [NSString stringWithFormat:@"%i",(k+1)+(l*5)];
CCButton *tempButton;
tempButton = [CCButton buttonWithTitle:tempTitle]
tempButton.block = ^(id sender) {
int row = floorf(touchLocation.y/(screenBounds.size.height/6)) + 1;
int column = floorf(touchLocation.x/(screenBounds.size.width/4)) + 1;
int buttonIndex = row*column;
for (int m = 1; m < buttonIndex; m++) {
[[LevelManager sharedInstance] nextLevel];
}
CCScene *gameplayScene = [CCBReader loadAsScene:@"LevelScene"];
[[CCDirector sharedDirector] replaceScene:gameplayScene];
levelNumber = i;
};
tempButton.position = ccp((screenBounds.size.width/4)*j + levelImagePlaceholder.contentSize.width*tempButton.scale, screenBounds.size.height/6*k + 50 + l*screenBounds.size.height);
[self addChild:tempButton];
i++;
}
}
}
获取触摸位置的方法
-(void) touchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
CCLOG(@"touch ran");
touchLocation = [touch locationInNode:self];
}
已经有可用的行/列。它们是j和k。这些变量可以在按钮的"on pressed"块中引用。