如何检测两个精灵之间的碰撞

时间:2013-09-25 09:14:24

标签: objective-c cocos2d-iphone collision-detection

我有两个精灵:一个角色精灵,另一个是障碍精灵。障碍精灵是另一个叫做bgSprite的精灵的孩子,它不断移动。我怎样才能检测到它们之间的碰撞。请帮我。提前谢谢你 这是一些代码:

[[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];

//障碍

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];
    }    
}

并在更新中:

if (CGRectIntersectsRect(self._character.boundingBox, obstacle.boundingBox))
{
    isTouchActive=NO;

    NSLog(@"collision");
}

1 个答案:

答案 0 :(得分:1)

问题在于父母。 _字符的父母和障碍的父母不是相同的CCNode,因此他们的位置没有共同的空间。您需要将一个boundingBox的位置转换为另一个空格。

编辑:

 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");
    }