Tuesday, October 25, 2011

Added Bullet/Wall Collision...

OK, I found a major no-no I was doing in my SmashPcBullet deconstructor; I wasn't removing and freeing the physics body/shape from the world. And, that was bad. So, I've fixed that.

Get the code here:
SmashPC 11-25-11_2 Collision

Here's the fixed deconstructor:
SmashPcBullet::~SmashPcBullet()
{
    delete mpSprite;

    if (mBulletDetails.pGlowImage)
    {
        delete mpGlowSprite;
    }

    cpSpaceRemoveBody(mpSpace, mpBody);
    cpSpaceRemoveShape(mpSpace, mpShape);

    cpBodyFree(mpBody);
    cpShapeFree(mpShape);

}

And, I added this line in the constructor to add a collision handler:
    // Create Collision handler here, only wall notifies the bullet
    // other handlers get notifed of hit by bullet
    // data can be NULL since we have class stored in Shape
    cpSpaceAddCollisionHandler(mpSpace, BULLET_COL_TYPE, WALL_COL_TYPE, SmashPcBullet::WallCollision, NULL, NULL, NULL, NULL);

This call sets the function SmashPcBullet::WallCollision as the callback for collisions between type BULLET_COL_TYPE (which is all bullets) and WALL_COL_TYPE (all walls).
And, here's WallCollision (defined static in header file):
int SmashPcBullet::WallCollision(cpArbiter *arb, struct cpSpace *space, void *data)
{
    SmashPcBullet *pBullet;
    cpShape *pBulletShape, *pWallShape;
    cpArbiterGetShapes(arb, &pBulletShape, &pWallShape);

    printf("Callback!\n");

    pBullet = reinterpret_cast(pBulletShape->data);

    // Mark bullet for removal
    pBullet->SetDead();
}
If you recall, in the SmashPcBullet constructor, we assign mpShape->data = this.  So, in the callback, we can extract the Bullet class and set it to Dead, so it will be removed.

Here's a in-game picture shooting bullets against the wall:

No comments:

Post a Comment