0
votes

I'm building a cocos2d iPhone game with lots of bullets and moving enemies and I'm detecting collisions between them. Every sprite can be represented by a circle for collision purposes. I'm considering the following options:

1) Simple Sphere Detection

I detect like this at regular intervals:

-(BOOL) isCollidingSphere:(CCSpriteExt*) obj1 WithSphere:(CCSprite *) obj2
{
    float minDistance = obj1.radius + obj2.radius;
    float dx = obj2.position.x - obj1.position.x;
    float dy = obj2.position.y - obj1.position.y;
    if (! (dx > minDistance || dy > minDistance) )
    {
        float actualDistance = sqrt( dx * dx + dy * dy );
        return (actualDistance <= minDistance);
    }
    return NO;
}

2) Box2d for collision detection only

I create a Box2d body for all sprites as shown in this tutorial: http://www.raywenderlich.com/606/how-to-use-box2d-for-just-collision-detection-with-cocos2d-iphone

My question is simple: If my priority is optimisation, which approach is faster?

Thanks!

1

1 Answers

1
votes

If all you need is distance/radius based collision checks, you don't need a physics engine.

You should get rid of the sqrt though. First of all, you're using the square root function that works on doubles. For the float version use sqrtf.

To get rid entirely of the square root, make sure your objects store their radius squared (radiusSquared = radius * radius). That way you don't have to take the square root anymore:

-(BOOL) isCollidingSphere:(CCSpriteExt*) obj1 WithSphere:(CCSprite *) obj2
{
    float r1 = obj1.radius;
    float r2 = obj2.radius;
    float minDistanceSquared = r1 * r1 + r2 * r2 + 2 * r1 * r2;
    float dx = obj2.position.x - obj1.position.x;
    float dy = obj2.position.y - obj1.position.y;
    float actualDistanceSquared = dx * dx + dy * dy;
    return (actualDistanceSquared <= minDistanceSquared);
}