Home > iPhone Development > How to Use DebugDraw of Box2d with Cocos2d

How to Use DebugDraw of Box2d with Cocos2d

Cocos2d-iPhone just released v0.8.1-Beta. A great news is DebugDraw of Box2D works with Cocos2d now. I tried DebugDraw with Cocos2d v0.8.0 before, but nothing shows up. In this article, I will briefly introduce how to use DebugDraw with Cocos2d v0.8.1-Beta. Note: The following example is based on the article How to Implement Grabbing a Sprite with Cocos2d and Box2d. I used DebugDraw instead of the ball sprite. Another thing should be noticed is something changed in Box2d. For example, b2Body::CreateShape is removed, you should use b2Body::CreateFixture instead. You can see some changes from the source codes of following example.

DebugDraw is a very useful tool for verifying simulating and speeding up your game development. At the initial stage of development, you usually don’t want to think much of graphics, so you can use DebugDraw to help draw physics entities. When you are confident about the game logic, simulation or some other important things, you can use your own pretty sprites to replace DebugDraw.

In order to use DebugDraw, you need two steps:

Step 1: Setup DebugDraw in initialization. To use DebugDraw of Box2d, normally we need to inherit from class DebugDraw and implement our own methods (e.g., DrawPolygon, DrawSolidCircle, etc.) of drawing physics entities.  In Cocos2d, we can easily use GLESDebugDraw instead of implementing our own ones. Therefore, in the initialization function, simply add the following codes:

m_debugDraw = new GLESDebugDraw(PTM_RATIO);
	uint32 flags = 0;
	flags += 1	* b2DebugDraw::e_shapeBit;
	flags += 1	* b2DebugDraw::e_jointBit;
	flags += 1	* b2DebugDraw::e_controllerBit;
	flags += 1	* b2DebugDraw::e_coreShapeBit;
	flags += 1	* b2DebugDraw::e_aabbBit;
	flags += 1	* b2DebugDraw::e_obbBit;
	flags += 1	* b2DebugDraw::e_pairBit;
	flags += 1	* b2DebugDraw::e_centerOfMassBit;
	m_debugDraw->SetFlags(flags);
	world->SetDebugDraw(m_debugDraw);

The value of flags determines what kind of things you want to draw. You can set your own value of flags.

Step 2: Add b2World::DrawDebugData in draw method. In Cocos2d, drawing stuff should be placed in draw method.

-(void) draw{
	[super draw];
	glEnableClientState(GL_VERTEX_ARRAY);
	world->DrawDebugData();
	glDisableClientState(GL_VERTEX_ARRAY);
}

All done!

————————-

Download: You can download the source codes from here.

Categories: iPhone Development
  1. August 11th, 2009 at 12:02 | #1

    Wow!

    This is exactly what I have been looking for! So far I’m liking the look of Box2D. DebugDraw is going to help save so much time!!! Thanks for your extremely useful articles!

  2. August 11th, 2009 at 23:09 | #2

    Cool!It’s really a useful article.Thanks for your effort and share.

  3. afzal
    September 7th, 2009 at 22:30 | #3

    nice but plz give full information and code to enhance yr blog

  1. August 12th, 2009 at 17:11 | #1