2012-02-13 62 views
0

試用Cocos2D集合檢測並且有一些問題。首先,一些背景:Cocos2D:從循環訪問對象CGRect

這是我向我的遊戲中添加新項目的方法,位於與我的遊戲圖層不同的課程中。這是位於我的項目類:

-(void) addItem:(NSString *) theFileName: (NSMutableArray *) theArray{ 

     CCSprite *item = [CCSprite spriteWithFile:theFileName 
              rect:CGRectMake(0, 0, 50, 50)]; 

     //Positions 


     int minX = 160; 
     int maxX = 360; 
     int xRange = maxX - minX; 
     int xCord = (arc4random() % xRange) + minX; 


     item.position = ccp(xCord, -5); 

    [self addChild:item]; 

    [theArray addObject:item]; 

然後,我在我的遊戲層使用此方法,使用到名爲ItemManager項目類的引用:

[ItemManager addItem:@"box.png" :itemList];  

如果我要進行碰撞檢測在兩個精靈之間,在這種情況下是一個盒子和其他東西,我需要能夠使用addItem方法中創建的方框rect。

for(CCSprite *newItem in itemList){ 
//(if box rectangle collides with my players or whatever 

} 

那麼我怎樣才能訪問在原始方法中創建的矩形?

謝謝。

回答

0

在這種情況下,我會建議使用CCSprite的boundingBox的屬性衝突檢測:

例子:

for(CCSprite *newItem in itemList) 
{ 
    // if box rectangle collides with my players or whatever 
    if (CGRectContainsRect([newItem boundingBox], [player boundingBox])) 
     // do something 
} 
+0

歐凱,似乎工作,感謝的人!你知道,如果精靈實際上在它周圍有一個矩形,它是否重要?我的意思是boudingBox的數量是否等於矩形?歡迎您來訪: – Alouette 2012-02-13 11:53:53

+0

)我不太瞭解您的問題。你可以嘗試重新翻譯一下或者給出一個具體的例子嗎?爲了進一步解釋,這個boundingBox基本上只是一個圍繞你的精靈的軸對齊的邊界矩形(即使你縮放或旋轉它)。要更好地顯示此邊界框,請轉到您的cocos2d文件夾中的ccConfig.h並設置#define CC_SPRITE_DEBUG_DRAW 1. – 2012-02-13 12:36:00

+0

啊,這是一個很棒的功能! (爲了調試的目的)。那麼,我的問題實際上在boudingBox被抽出時得到了答案。再次感謝,感謝它! – Alouette 2012-02-13 12:48:00