0
我無法檢測到兩個精靈之間的碰撞,一個正在移動。Cocos2d動作期間的Sprite衝突檢測
我有類「敵人」的子畫面,經由CCMoveTo在屏幕上移動,並且類「英雄」的另一子畫面,通過觸摸控制,既加入到上級「MainGame」場景
以下表明這兩個精靈是如何加入到場景上,敵人付諸行動:
MainGame.m
-(id) init{
if((self=[super init])) {
_enemies = [[NSMutableArray alloc]init];
_enemyLink = [Enemy nodeWithTheGame:self];
_enemyLink.position = ccp(10, 10);
[self.enemies addObject:_enemyLink];
CCMoveTo *test = [CCMoveTo actionWithDuration:40 position:ccp(500, 250)];
[_enemyLink runAction:test];
_heroArray = [[NSMutableArray alloc]init];
_heroLink = [Hero nodeWithTheGame:self location:ccp(100,100)];
[_heroArray addObject:_heroLink];
[self scheduleUpdate];
}
}
-(void)update:(ccTime)delta{
if (CGRectIntersectsRect([self.enemyLink.enemySprite boundingBox], [self.heroLink.heroSprite boundingBox])) {
NSLog(@"rect intersects rect");
}
for (CCSprite *enemies in self.enemies) {
NSLog(@"enemy position: %f, %f",enemies.position.x,enemies.position.y);
}
}
我無法在和ACTI後檢測這兩個精靈之間的碰撞上。但是,如果我將英雄移動到場景中的位置(0,0),我的代碼中的日誌將觸發,並且這兩個人將進行攻擊。
更新中的for循環表示敵對精靈位置在動作過程中不斷移動。因此,爲什麼我難以理解爲什麼碰撞沒有被發現。
你是正確的Loic,使用一個類似的for循環來檢查英雄類實例的x,y座標,表明它並沒有在世界空間中更新,並且始終在0,0,即使這個sprite被移動。你知道我怎麼能改變英雄精靈座標系嗎?我試圖調用[hero.parent convertToWorldSpace:hero.position];沒有太大的成功。 –
本質上,計算第一個精靈的矩形,然後使用它們的位置計算第二個精靈的矩形。像這樣:http://stackoverflow.com/questions/5822077/cocos2d-sprite-collision-detection-boundingbox。對於每個精靈,使用正確的位置投射到相同的座標系(這取決於您自己的節點層次結構),如下所示:http://stackoverflow.com/questions/16268213/a-sprite-bounding-box-shows-wrong-位置後運動的層。希望這可以幫助。 –
此外,請注意,如果您開始旋轉您的精靈並應用其他轉換,它會變得更加複雜。在這種情況下,您需要在計算中考慮這一點。但如果你到達那裏,你可能會考慮花栗鼠或Box2d。 –