Reputation: 440
I have an array called spriteArray:
@property (retain) NSMutableArray *spriteArray;
@synthesize spriteArray = spriteArray_;
And I have a sprite:
@property (nonatomic, assign) CCSprite *sprite;
@synthesize sprite = sprite_;
I create a certain number of sprites depending on the value of spriteNumber (an integer):
for (int i = 0; i < spriteNumber; i++) {
if ([spritetype_ isEqualToString:@"typeOne"]) {
self.sprite = [[typeOne alloc] initTypeOne];
self.sprite.position = randomPoint;
[self.spriteArray addObject:self.sprite];
[self addChild:self.sprite];
}}
The sprites initialise successfully, and appear on the screen as they should. However, when I try to use them for collision detection, only one of them works:
if (CGRectIntersectsRect(self.sprite.boundingBox, self.swat.boundingBox)) {
//swat is another sprite
NSLog(@"detected");
}
What I wanted is to 'index' each of the sprites as they are being created, so that the collision detection works.
SAMPLE CODE: http://pastebin.com/swNUwB6U
Upvotes: 0
Views: 75
Reputation: 1283
Use the tag property for the sprite.
for (int i = 0; i < spriteNumber; i++) {
if ([spritetype_ isEqualToString:@"typeOne"]) {
typeOne *typeOneSprite = [[typeOne alloc] initTypeOne];
typeOneSprite.position = randomPoint;
// USE TAG!
typeOneSprite.tag = i;
[self.spriteArray addObject:typeOneSprite];
[self addChild:typeOneSprite];
// Don't forget to release if you are not using ARC.
}}
Then call the tag value in the collision detection code.
[self.spriteArray enumerateObjectsUsingBlock:^(id obj, NSUInteger index, BOOL *stop)
{
typeOne *spriteOne = (typeOne *)obj;
if (CGRectIntersectsRect(spriteOne.boundingBox, self.swat.boundingBox))
{
//swat is another sprite
if (spriteOne.tag == numberyouwant){}
NSLog(@"detected");
}
}];
Upvotes: 2