我同意,如果您的棋盘完全是静态的,似乎没有必要为棋盘上的每个游戏方块创建一个精灵。
然而 CGRect 不是一个对象类型,所以它不能被添加到 NSMutableArray 中,而且我还假设在某些时候你会想要对你的游戏方块做其他事情,比如突出显示它们和其他东西。我建议你做的是创建一个名为 GameSquare 的类,它继承自 CCNode 并将它们放入一个数组中:
// GameSquare.h
@interface GameSquare : CCNode {
//Add nice stuff here about gamesquares and implement in GameSquare.m
}
之后,您可以将 gamesquares 创建为节点:
// SomeLayer.h
@interface SomeLayer : CCLayer {
NSMutableArray *myGameSquares;
GameSquare *magicGameSquare;
}
@property (nonatomic, strong) GameSquare *magicGameSquare;
// SomeLayer.m
/* ... (somewhere in the layer setup after init of myGameSquares) ... */
GameSquare *g = [[GameSquare alloc] init];
g.position = CGPointMake(x,y); //replace x,y with your coordinates
g.size = CGSizeMake(w,h); //replace w,h with your sizes
[myGameSquares addObject:g];
self.magicGameSquare = [[GameSquare alloc] init];
magicGameSquare.position = CGPointMake(mX,mY); //replace with your coordinates
magicGameSquare.size = CGSizeMake(mW,mH); //replace with your sizes
之后,您可以像这样(在您的 CCLayer 子类中)对 gamesquares 进行命中测试:
// SomeLayer.m
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
CGPoint location = [self convertTouchToNodeSpace: touch];
// Example of other objects that user might have pressed
if (CGRectContainsPoint([magicSquare getBounds], location)) {
// User pressed magic square!
[magicSquare doHitStuff];
} else {
for (int i=0; i<myGameSquares.count; i++) {
GameSquare *square = [myGameSquares objectAtIndex:i];
if (CGRectContainsPoint(square.boundingBox, location)) {
// This is the square user has pressed!
[square doHitStuff];
break;
}
}
}
return YES;
}
是的,您必须浏览列表,但除非玩家可以一次按多个方格,否则您可以在找到正确的方格后立即停止搜索,如示例中所示。
(假设使用 ARC)
PS。如果您在某些时候需要为 GameSquare 添加任何精灵,只需在您的 GameSquare 类中添加一个 CCSprite 成员并引用它。