我同意,如果你的主板完全是靜態的,那麼在你的主板上爲每個遊戲方塊創建一個精靈似乎沒有必要。
然而,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
之後,你可以做碰到這樣的gamesquares測試(在CCLayer子類):
// 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;
}
是的,你將不得不通過名單看,但除非玩家可以按許多SQUAR只要一觸即發,只要找到正確的一個,就可以停止搜索,如示例中所示。
(假定使用ARC)
PS。如果您在某些時候需要爲GameSquare添加任何精靈,只需在您的GameSquare類中添加一個CCSprite成員並引用它即可。
謝謝,這確實是最簡單的答案,最靈活的前進。如果我在路上遇到問題,我只能使用它來尋找其他方法。謝謝 – smilinfoo 2012-08-16 17:55:13
這不是什麼奇怪的事情,這是一個非常直接和線性的方法。如果你想擴展CCNode或者只是簡單地實現它,但是爲每個方塊保留一個類並且通過檢查列表來檢查觸摸碰撞是非常標準的,那麼這是可選的。在某些情況下,對列表進行排序可能會有所幫助,但在這裏並不是真的,因爲您不知道用戶將按哪個屏幕。一個明顯的改進可能是在檢查其餘部分之前,檢查遊戲棋子首先在哪個方格上的碰撞。 – 2012-08-17 08:05:37