I am fairly new to Box2D, and I really need your help on that one! In my game, which is using Cocos2D for iPhone, I want my bodies to break things if they travel at a given velocity. Right now, all my bodies are dynamics and not sensors. When there's a collision, I call a function which determines if wether or not the crate should break. Here's the code :
- (void) contactWithPlayer:(Player *)_player{
float recquiredVelocity = 8.5;
b2Vec2 vel = _player.body->GetLinearVelocity();
float playerVelocity = ABS(vel.x) + ABS(vel.y);
NSLog(@"Player speed : %f", playerVelocity);
if (playerVelocity >= recquiredVelocity) {
[self breakCrate]; //Function that destroy the crate's body in the b2world
}
}
Everything works fine, but what I'd like to achieve is my player to go through the object if the crate breaks, at a reduced speed. Right now, my player only bounces on it! I've tried to re-use the vel
variable and apply it to the player's body, but at that step the player already started moving in the other direction! I've tried to reduce the crate's density, but it just doesn't feel natural!
Does anyone have a solution for this? Thanks in advance!
EDIT : The code I am using right now is a code borrowed on Ray Wenderlich's tutorials about colliding two objects using Box2D. So I have a class called MyContactListener
that adds colliding objects in a vector, which is used later in my update loop in my game scene. Here's the update loop :
- (void) update:(ccTime)delta{
[self checkCollision];
}
- (void) checkCollisions{
//COLLISIONS
std::vector<MyContact>::iterator pos;
for(pos = _contactListener->_contacts.begin(); pos != _contactListener->_contacts.end(); ++pos) {
MyContact contact = *pos;
b2Body *bodyA = contact.fixtureA->GetBody();
b2Body *bodyB = contact.fixtureB->GetBody();
if (bodyA->GetUserData() != NULL && bodyB->GetUserData() != NULL) {
GameObject *spriteA = (GameObject *)bodyA->GetUserData();
GameObject *spriteB = (GameObject *)bodyB->GetUserData();
if (spriteA.type == o_PLAYER && spriteB.type != o_PLAYER) {
[spriteB contactWithPlayer:(Player*)spriteA];
}else if (spriteB.type == o_PLAYER && spriteA.type != o_PLAYER){
[spriteA contactWithPlayer:(Player*)spriteB];
}
}
}
}
Thanks!