cocos2d精灵碰撞

时间:2011-12-02 13:37:24

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

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

所有精灵都一下子移动到屏幕上的随机点。

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

有可能吗?

3 个答案:

答案 0 :(得分:3)

遍历数组中的每个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];

答案 1 :(得分:1)

看看这个S.O. answers

您可以使用CGRectIntersectsRect和节点boundingBox进行简单的碰撞检测。如果您需要更多高级功能,请查看chipmunkBox2D等物理引擎。

答案 2 :(得分:0)

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

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