2013-09-25 74 views
-3

我有两个精灵:一个字符精灵,另一个是障碍精灵。障碍精灵是另一个精灵,称为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"); 
} 
+0

使用CGRectIntersectRect([characterSprite textrureRect],[obstacleSprite textureRect]); – Renaissance

+0

它不能在正确的位置工作 – Nidhi

+0

你能为你的问题添加一些代码吗? – Renaissance

回答

1

问题出在家长。 _character的父母和障碍父母不是同一个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"); 
    } 
+0

这是行不通的。 – Nidhi

+0

立即尝试,我在一行中犯错。 –

+0

碰撞检测到但不在完美的位置。检测一段距离后 – Nidhi