I have two sprites:one character sprite and another one is obstacle sprite. obstacle sprite is child of another sprite called bgSprite which is continuously moving. How can i detect collision between them. Please help me. Thanks in advance
Here is some code:
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"BoyRunAnimation.plist"];
CCSpriteBatchNode *spriteSheet = [CCSpriteBatchNode batchNodeWithFile:@"BoyRunAnimation.png"];
[self addChild:spriteSheet];
self._character = [CCSprite spriteWithSpriteFrameName:@"Boy_Run_0003.png"];
self._character.position = ccp(80, 150);
[spriteSheet addChild:self._character];
[self boyRunningAnimation];
//obstacles
for (int i=0; i<5; i++)
{
int xPos=500+500*i;
if (xPos<2*_roadImage1.contentSize.width)
{
CCSprite *obstacle=[CCSprite node];
obstacle.textureRect=CGRectMake(0, 0, 50, _roadImage1.contentSize.height);
obstacle.color=ccc3(255, 255,255);
if (xPos <= _roadImage1.contentSize.width)
{
obstacle.position=ccp(xPos, _roadImage1.contentSize.height/2);
[_roadImage1 addChild:obstacle z:0 tag:1];
}
else
{
obstacle.position=ccp(xPos-_roadImage1.contentSize.width, 60);
[_roadImage2 addChild:obstacle z:0 tag:2];
}
[obstacleArray addObject:obstacle];
}
}
and in the update:
if (CGRectIntersectsRect(self._character.boundingBox, obstacle.boundingBox))
{
isTouchActive=NO;
NSLog(@"collision");
}
The problem is in the parents. _character's parent and obstacle's parent isn't the same CCNode, so their positions don't have common space. You need to translate positions of one boundingBox to another space.
edit:
CCRect obstacleBox = [obstacle boundingBox];
CCPoint obstaclePosition = obstacleBox.origin;
obstaclePosition = [[obstacle parent] convertToWorldSpace:obstaclePosition];
obstaclePosition = [[self._character parent] convertToNodeSpace:obstaclePosition];
obstacleBox.origin = obstaclePosition;
if (CGRectIntersectsRect(self._character.boundingBox, obstacleBox))
{
isTouchActive=NO;
NSLog(@"collision");
}