Bombs with Box2D & Cocos2D

Here is some example code based off my tutorial on how to implement orbital / radial gravity, but in reverse. This example pushes objects away instead of pulling inward. It makes for a nice explosion effect. Much work would need to be done to make it realistic, but you get the general idea of how to blow things up. You need to have Cocos2D and Box2D installed. Box2D comes packaged with the latest version if Cocos2D.




Download Source Code for this tutorial:
Bomb Demo Box2d & Cocos2d Example Source Code – 799k

Random Posts:

If you found this useful, shoot me a small donation or at the very least leave a comment, every bit of encouragement helps keep me motivated to update with more content on a regular basis!

Comments

*

6 Responses to “Bombs with Box2D & Cocos2D”

  1. afour says:

    Thanks for this… I modified it a little to make a more realistic explosion. I added a ‘bomblife’ variable that turns off the bomb gravity after a set period of ticks. This makes the falling blocks fall without being pushed away from the circles.

    Like this:

    -(void) tick: (ccTime) dt
    {
    	//It is recommended that a fixed time step is used with Box2D for stability
    	//of the simulation, however, we are using a variable time step here.
    	//You need to make an informed choice, the following URL is useful
    	//http://gafferongames.com/game-physics/fix-your-timestep/
     
    	int32 velocityIterations = 8;
    	int32 positionIterations = 1;
     
    	// Instruct the world to perform a single step of simulation. It is
    	// generally best to keep the time step and iterations fixed.
    	world->Step(dt, velocityIterations, positionIterations);
     
     
    	//Iterate over the bodies in the physics world
    	for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
    	{
    		if(bomb)
    		{
    			if (bomblife > 0)
    			{
    				b2Body* ground = planet->GetBody();
    				b2CircleShape* circle = (b2CircleShape*)planet->GetShape();
    				// Get position of our "Planet" - Nick
    				b2Vec2 center = ground->GetWorldPoint(circle->m_p);
    				// Get position of our current body in the iteration - Nick
    				b2Vec2 position = b->GetPosition();
    				// Get the distance between the two objects. - Nick
    				b2Vec2 d = center - position;
    				// The further away the objects are, the weaker the gravitational force is - Nick
    				float force = kRADIAL_GRAVITY_FORCE / d.LengthSquared(); // 150 can be changed to adjust the amount of force - Nick
    				d.Normalize();
    				b2Vec2 F = force * d;
    				// Finally apply a force on the body in the direction of the "Planet" - Nick
    				b->ApplyForce(F, position);
    				bomblife--;
    			}
    			else {
    				bomb = NO;
    			}
     
    		}
     
    		if (b->GetUserData() != NULL) {
    			//Synchronize the AtlasSprites position and rotation with the corresponding body
    			CCSprite *myActor = (CCSprite*)b->GetUserData();
    			myActor.position = CGPointMake( b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO);
    			myActor.rotation = -1 * CC_RADIANS_TO_DEGREES(b->GetAngle());
    		}	
    	}
    }
     
    - (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
    {
    	//Add a new body/atlas sprite at the touched location
    	for( UITouch *touch in touches ) {
    		CGPoint location = [touch locationInView: [touch view]];
     
    		location = [[CCDirector sharedDirector] convertToGL: location];
     
    		if(!bomb) {
    			// Create our static "Planet" - Nick
    			b2CircleShape shape;
    			shape.m_radius = 0.5f;
    			shape.m_p.Set(location.x / PTM_RATIO,location.y / PTM_RATIO);
    			b2FixtureDef fd;
    			fd.shape = &shape;
    			planet = groundBody->CreateFixture(&fd);
    			// End Create Planet - Nick
    			bomb = YES;
    			bomblife = 120;
    		}
    	}
    }
  2. Nick Vellios says:

    Funny you posted this. I was just thinking yesterday how I wanted to implement a timer to turn off the force. Thank you! I will be updating this in the next week or so to implement something like this.

  3. [...] Nick Vellios wrote a series on adding radial gravity to Box2D. (h/t: [...]

  4. koss says:

    Thank you for this tutorial! I also add the new bomblife too and it works great! I have a question… How would you change your code to NOT explode but IMPLODE? I kind of newbie :)

  5. Makyfa says:

    Thanks Dan! This is great!

    I’m having some trouble iterating on this though. I’d love to be able to delete the bomb’s b2Body and let the user create an additional bomb.

    Every time that I remove the body though, I lose the ability to add additional bombs. Do I need to add the bombs to some sort of list before I remove their b2Body? How would I go about that?

    Thanks so much!

  6. random says:

    Very cool. Thanks for posting this. After playing around a bit I decided to use ApplyLinearImpulse instead of ApplyForce. Then you can turn it off after one tick and get essentially the same result.

Twitter Me