Cocos2d精灵碰撞



我有一个同时显示的CCSprites数组。每个精灵都有一个移动路径,移动路径是屏幕上的一个随机点。

所有精灵都同时移动到屏幕上的随机点。

我想做的是检测精灵之间的碰撞,然后改变它们的移动路径。

有可能吗?

遍历数组中的每个CCSprite(称为 A ),并且对于每次迭代再次遍历数组中的每个CCSprite(当然不包括 A 本身)(称为 B )。现在,使用CGRectIntersectsRectboundingBox来找到它们之间的冲突。它是这样的:

        for (CCSprite *first in mySprites) {
            for (CCSprite *second in mySprites) {
                if (first != second) {
                    if (CGRectIntersectsRect([first boundingBox], [second boundingBox])) {
                        // COLLISION! Do something here.
                    }
                }
            }
        }

编辑:当然,如果两个精灵发生碰撞,"碰撞事件"可能会发生两次(首先从精灵A的角度来看,然后从精灵B的角度来看)。

如果你只希望碰撞事件在每次检查时触发一次,你需要记住碰撞对,这样你就可以忽略在检查时已经发生的碰撞。

有无数种方法可以检查,但这里有一个例子(更新的代码):

再次编辑:

NSMutableArray *pairs = [[NSMutableArray alloc]init];
    bool collision;
    for (CCSprite *first in mySprites) {
        for (CCSprite *second in mySprites) {
            if (first != second) {
                if (CGRectIntersectsRect([first boundingBox], [second boundingBox])) {
                    collision = NO;
                    // A collision has been found.
                    if ([pairs count] == 0) {
                        collision = YES;
                    }else{
                        for (NSArray *pair in pairs) {
                            if ([pair containsObject:first] && [pair containsObject:second]) {
                                // There is already a pair with those two objects! Ignore collision...
                            }else{
                                // There are no pairs with those two objects! Add to pairs...
                                [pairs addObject:[NSArray arrayWithObjects:first,second,nil]];
                                collision = YES;
                            }
                        }
                    }
                    if (collision) {
                        // PUT HERE YOUR COLLISION CODE.
                    }
                }
            }
        }
    }
    [pairs release];

看看这些sos的答案。

您可以使用CGRectIntersectsRect和节点boundingBox进行简单的碰撞检测。如果你需要更高级的功能,可以考虑花栗鼠或Box2D等物理引擎。

Ray Wenderlich写了一个关于使用Box2D进行碰撞检测的很好的教程,如果你对这种方式感兴趣的话。http://www.raywenderlich.com/606/how-to-use-box2d-for-just-collision-detection-with-cocos2d-iphone

首先检查你的精灵是否可以用矩形近似。如果是这样,那么@Omega的回答很棒。如果它们不能,也许是因为它们包含很多透明度或其他原因,你可能需要用多边形近似你的精灵,并使用它们。

最新更新