Ashley Staggs
Ashley Staggs

Reputation: 1567

Simple Cocos2d Box2d Action On Collision

I have been looking for weeks for an OBJ-C based tutorial on how to call a method when a specific b2body collides with something else (not everything).

Basically, a block falls to the ground every second. This works fine, but when it hits the ground or the player, the block should get deleted and pieces of it (different object) should be spawned.

Can anyone tell me how to do this?

Any help would be hot

Thanks

Upvotes: 0

Views: 805

Answers (2)

Ashley Staggs
Ashley Staggs

Reputation: 1567

I have realized that as my object fall to the ground, i could create my own VERY simple physics by creating a start velocity, and then increasing it in the update method by a specific amount.

For the collision, my objects all fit in a 48pt wide grid so i could do simple rectangular collision detection.

Upvotes: 0

Anish
Anish

Reputation: 2917

I think this is the one that you need..You need to include MycontactListener

-(void) checkForHit{

std::vector<b2Body *>toDestroy;

std::vector<MyContact>::iterator pos;

for(pos = _contactListener->_contacts.begin(); pos != _contactListener->_contacts.end(); ++pos) {

MyContact contact = *pos;

bodyA = contact.fixtureA->GetBody();

bodyB = contact.fixtureB->GetBody();

if (bodyA->GetUserData() != NULL && bodyB->GetUserData() != NULL) {

spriteA = (CCSprite *) bodyA->GetUserData();

spriteB = (CCSprite *) bodyB->GetUserData();

//NSLog(@”sprite tag is  %d”,spriteA.tag);

if (spriteA.tag == 50)  {

if (std::find(toDestroy.begin(), toDestroy.end(), bodyB) == toDestroy.end()) {

toDestroy.push_back(bodyB);
}

}

std::vector<b2Body *>::iterator pos2;
for(pos2 = toDestroy.begin(); pos2 != toDestroy.end(); ++pos2) {
b2Body *body = *pos2;
if (body->GetUserData() != NULL) {
CCSprite *sprite = (CCSprite *) body->GetUserData();
[self removeChild:sprite cleanup:YES];
}
_world->DestroyBody(body);
}

or if you dont't want to use contact listener.you can create a fixture for ground body and a body that u want to destroy and use the following code to check if it is intersecting and destroy it...

if((contact.fixtureA == groundFixture && contact.fixtureB == bodyFixture) ||
    (contact.fixtureA == bodyFixture&& contact.fixtureB == groundFixture ))
    {
    //destroy the body
    }

Upvotes: 1

Related Questions