post

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.

Posted on 10th August 2009 in iPhone Development  •  No comments yet

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>