2013-09-25 76 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