2

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

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

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

是否可以?

4

3 回答 3

2

遍历CCSprite数组中的每一个(调用它A),并为每次迭代再次遍历CCSprite数组中的每一个(当然不包括A它自己)(调用这个B)。现在,使用CGRectIntersectsRectwithboundingBox来查找它们之间的碰撞。它是这样的:

        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];
于 2011-12-02T16:18:53.803 回答
1

看看这个SO 答案

您可以使用CGRectIntersectsRect和 节点进行简单的碰撞检测boundingBox。如果您需要更高级的功能,请查看像花栗鼠Box2D这样的物理引擎。

于 2011-12-02T14:14:14.827 回答
0

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

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

于 2011-12-04T10:37:01.587 回答