<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" version="2.0">

<channel>
	<title>Uchidacoonga</title>
	
	<link>http://www.uchidacoonga.com</link>
	<description>"Do it until it becomes boring, then keep doing it until it becomes beautiful."</description>
	<lastBuildDate>Tue, 13 Sep 2011 17:14:48 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1.4</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/uchidacoonga/feed" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="uchidacoonga/feed" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><feedburner:emailServiceId xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">uchidacoonga/feed</feedburner:emailServiceId><feedburner:feedburnerHostname xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://feedburner.google.com</feedburner:feedburnerHostname><item>
		<title>Box2d Collision Filtering Demystified</title>
		<link>http://www.uchidacoonga.com/2011/09/box2d-collision-filtering-demystified/</link>
		<comments>http://www.uchidacoonga.com/2011/09/box2d-collision-filtering-demystified/#comments</comments>
		<pubDate>Tue, 13 Sep 2011 17:03:18 +0000</pubDate>
		<dc:creator>Min</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://www.uchidacoonga.com/?p=1177</guid>
		<description><![CDATA[To Collide or Not to Collide When you create simple Box2d objects, they will collide with each other. But what if you do not want an object colliding with all other objects? What if you want certain objects colliding with only certain other objects? How do we achieve this finer grained control? Say that our <a href='http://www.uchidacoonga.com/2011/09/box2d-collision-filtering-demystified/'>... [READ THE FULL ARTICLE]</a>]]></description>
			<content:encoded><![CDATA[<h4><span style="color: #ff6600;"><strong>To Collide or Not to Collide</strong></span></h4>
<p>When you create simple Box2d objects, they will collide with each other. But what if you do not want an object colliding with all other objects? What if you want certain objects colliding with only certain other objects? How do we achieve this finer grained control? </p>
<p>Say that our game has three game objects: 1. Player, 2. Enemies and 3. Power Ups. Normally, all three objects would collide with each other. But what if what we really want to do is this:</p>
<p>1. Player and enemies can collide<br />
2. Player and power ups can collide<br />
3. Enemies and power ups SHOULD NOT collide</p>
<p>There is something called a groupIndex. Two fixtures with the same positive groupIndex will always collide. And two fixtures with negative groupIndex will never collide. But what if we want an even finer grained control than this?</p>
<h4><span style="color: #ff6600;"><strong>Category Bits and Mask Bits</strong></span></h4>
<p>There are two properties called categoryBits and maskBits which you can set for a fixture. An integer is 16 bits, so you can have up to 16 different categories. What do I mean by this? See below for 16 possible categories (in binary and also in hex).</p>
<p>Category_01 = 0000 0000 0000 0001    (0&#215;0001)<br />
Category_02 = 0000 0000 0000 0010    (0&#215;0002)<br />
Category_03 = 0000 0000 0000 0100    (0&#215;0004)<br />
&#8230;<br />
Category_15 = 0100 0000 0000 0000    (0&#215;4000)<br />
Category_16 = 1000 0000 0000 0000    (0&#215;8000)</p>
<p>The categoryBits and maskBits can be used together with bitwise operators to control collision between objects.</p>
<h4><span style="color: #ff6600;"><strong>Example</strong></span></h4>
<p>So let us put the above information to practical use. We have three game objects, so we can define three categories for our game objects.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#define CATEGORY_PLAYER    0x0001     // 0000 0000 0000 0001</span>
<span style="color: #6e371a;">#define CATEGORY_ENEMY     0x0002     // 0000 0000 0000 0010</span>
<span style="color: #6e371a;">#define CATEGORY_POWERUP   0x0004     // 0000 0000 0000 0100</span></pre></div></div>

<p>When we define the fixture for our game objects, we can now set the categoryBits and the maskBits like so. The code below says that the player will collide with enemies and power ups.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;">b2FixtureDef playerFixture;
... 
playerFixture.filter.categoryBits <span style="color: #002200;">=</span> CATEGORY_PLAYER;
playerFixture.filter.maskBits <span style="color: #002200;">=</span> CATEGORY_ENEMY | CATEGORY_POWERUP;</pre></div></div>

<p>The code below says that the power up only collides with the player (and not enemies)</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;">b2FixtureDef powerupFixture;
... 
powerupFixture.filter.categoryBits <span style="color: #002200;">=</span> CATEGORY_POWERUP;
powerupFixture.filter.maskBits <span style="color: #002200;">=</span> CATEGORY_PLAYER;</pre></div></div>

<p>And finally, the code below says that enemies only collides with the player (and not the power up)</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;">b2FixtureDef enemyFixture;
... 
enemyFixture.filter.categoryBits <span style="color: #002200;">=</span> CATEGORY_ENEMY;
enemyFixture.filter.maskBits <span style="color: #002200;">=</span> CATEGORY_PLAYER;</pre></div></div>

<p>Once you set the categoryBits and maskBits, Box2d uses these and the rule below to determine whether the objects collide.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;">uint16 catA <span style="color: #002200;">=</span> fixtureA.filter.categoryBits;
uint16 maskA <span style="color: #002200;">=</span> fixtureA.filter.maskBits;
uint16 catB <span style="color: #002200;">=</span> fixtureB.filter.categoryBits;
uint16 maskB <span style="color: #002200;">=</span> fixtureB.filter.maskBits;
&nbsp;
<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#40;</span>catA <span style="color: #002200;">&amp;</span> maskB<span style="color: #002200;">&#41;</span> <span style="color: #002200;">!=</span> <span style="color: #2400d9;">0</span> <span style="color: #002200;">&amp;&amp;</span> <span style="color: #002200;">&#40;</span>catB <span style="color: #002200;">&amp;</span> maskA<span style="color: #002200;">&#41;</span> <span style="color: #002200;">!=</span> <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #11740a; font-style: italic;">// fixtures can collide</span>
<span style="color: #002200;">&#125;</span></pre></div></div>

<p>It is important to remember that if you want two fixtures to collide, the maskBits must include the categoryBits of the other fixture with which you want it to collide. Meaning, in the code below, the the player&#8217;s maskBits must include CATEGORY_ENEMY <strong>AND</strong> the enemy&#8217;s maskBits must also include CATEGORY_PLAYER. It is not enough to set it for just one of the fixtures. In other words, just because you set the player&#8217;s maskBits to collide with the enemy does not mean that they will collide. If A is set to collide with B, B must also be set to collide with A in order for the two to actually collide.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;">playerDef.categoryBits <span style="color: #002200;">=</span> CATEGORY_PLAYER;
playerDef.maskBits <span style="color: #002200;">=</span> CATEGORY_ENEMY;  <span style="color: #11740a; font-style: italic;">// &lt;-- point to the enemy</span>
&nbsp;
enemyDef.categoryBits <span style="color: #002200;">=</span> CATEGORY_ENEMY;
enemyDef.maskBits <span style="color: #002200;">=</span> CATEGORY_PLAYER;  <span style="color: #11740a; font-style: italic;">// &lt;-- point to the player</span></pre></div></div>

<h4><span style="color: #ff6600;"><strong>Conclusion</strong></span></h4>
<p>This should be fairly flexible enough for a great deal of your needs. If you need even more control than this, then I would suggest taking a look at Box2d&#8217;s contact listener&#8217;s PreSolve event (b2ContactListener::PreSolve).</p>
<p>Happy coding!</p>

<p><a href="http://feedads.g.doubleclick.net/~a/_tKaH23UQXA6KVKcnHZKLbJF870/0/da"><img src="http://feedads.g.doubleclick.net/~a/_tKaH23UQXA6KVKcnHZKLbJF870/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/_tKaH23UQXA6KVKcnHZKLbJF870/1/da"><img src="http://feedads.g.doubleclick.net/~a/_tKaH23UQXA6KVKcnHZKLbJF870/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.uchidacoonga.com/2011/09/box2d-collision-filtering-demystified/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Improve Performance and Reduce Memory with PVRTC Textures and Cocos2d</title>
		<link>http://www.uchidacoonga.com/2011/07/pvrtc-textures-and-cocos2d/</link>
		<comments>http://www.uchidacoonga.com/2011/07/pvrtc-textures-and-cocos2d/#comments</comments>
		<pubDate>Sun, 03 Jul 2011 17:35:52 +0000</pubDate>
		<dc:creator>Min</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[iPhone Development]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Cocos2D]]></category>

		<guid isPermaLink="false">http://www.uchidacoonga.com/?p=1130</guid>
		<description><![CDATA[Hello everyone! A few months have passed since I posted Simple Platformer Using Cocos2d and Box2d with Collision Detection. I have received many positive feedbacks and interest on the tutorial. I am glad that it has been helpful for so many in the community! Also, I would like to share the good news that the <a href='http://www.uchidacoonga.com/2011/07/pvrtc-textures-and-cocos2d/'>... [READ THE FULL ARTICLE]</a>]]></description>
			<content:encoded><![CDATA[<p>Hello everyone! A few months have passed since I posted <a href="http://www.uchidacoonga.com/2011/03/simple-platformer-using-cocos2d-and-box2d-with-collision-detection/">Simple Platformer Using Cocos2d and Box2d with Collision Detection</a>. I have received many positive feedbacks and interest on the tutorial. I am glad that it has been helpful for so many in the community! </p>
<p>Also, I would like to share the good news that the game we have been working on has been picked up by a major publisher. We hope to release it around September, so please stay tuned! The game has been built using the very same articles and tutorials found on this blog. </p>
<h4><span style="color: #ff6600;"><strong>What Is It?</strong></span></h4>
<p>PVRTC-I and -II are a family of lossy, fixed-rate texture compression formats used in PowerVR&#8217;s MBX and SGX technologies. PVRTC is the compressed texture format used in all generations of the iPhone, iPod Touch and iPad (<a href="http://en.wikipedia.org/wiki/PVRTC">source)</a>. You will see PVR and PVRTC being used interchangeably. They are not the same. They key thing to keep in mind is that a PVR is uncompressed, and PVRTC is compressed. Also, a PVR is a container which may contain various formats (a PVRTC is contained within a PVR file, for example). Some uncompressed PVR types are:</p>
<ul>
<li><strong>RGBA8888</strong>: 32-bit texture with alpha channel, best image quality</li>
<li><strong>RGBA4444</strong>: 16-bit texture with alpha channel, good image quality</li>
<li><strong>RGB565</strong>:  16-bit texture without alpha channel, good image quality but no alpha (transparency)</li>
</ul>
<p>Here are the PVRTC types,  which are compressed and lossy (meaning, quality is degraded):</p>
<ul>
<li><strong>PVRTC4BPP</strong>: Compressed format, 4 bits per pixel, ok image quality</li>
<li><strong>PVRTC2BPP</strong>: Compressed format, 2 bits per pixel, poor image quality</li>
</ul>
<h4><span style="color: #ff6600;"><strong>Pros and Cons</strong></span></h4>
<p>Why would you want to use a PVRTC texture? Because, it is the native texture format and is hardware accelerated. This translates to faster loading time than PNGs. Have you ever been plagued by long load times? Then PVRTC may be the answer. But even better, it will use less memory on the device and give you a performance boost. </p>
<p>It all sounds great! But wait, there is a downside. The downside is that because it is a lossy compression, the quality of your textures will suffer. Given a PNG of the same dimension, a PVRTC4BPP texture will take up more disk space <i>and</i> it will look worse (you will see artifacts, especially if you rely heavily on transparency or have a lot of gradients). </p>
<h4><span style="color: #ff6600;"><strong>Why Size Does Matter</strong></span></h4>
<p>As you may have already guessed, the amount of space used increases as the quality increases. This means RGBA8888 uses the most amount of space (in memory AND on disk). Here is a handy formula to calculate how much space will be used.</p>
<p><em>numBytes = width * height * bitsPerPixel / 8</em></p>
<p>What this means is that given a 1024&#215;1024 image, a RGBA8888 texture will require 4 MB of space. And a PVRTC4BPP will take 512 KB space. Why does size on disk matter at all? There is a very good reason for keeping the amount of space taken by your textures as low as possible.</p>
<p>This is due to the 20 MB size limit imposed by AT&#038;T (I do not know about Verizon or other international providers). If your application is over 20 MB, users will not be able to download your application over the air from their devices. They will have to go to a computer that has iTunes installed and download it from their Mac or PC. If you are working on a game, then you have to start rationing out disk space as textures aren&#8217;t the only assets that will require disk space (the other big one being audio).</p>
<p>So which one should you pick? A PNG will take less space on disk, but the loading time will be longer. The amount of space a PNG will take once loaded to memory is dependent on the pixel format that you set in Cocos2d, like so:</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">&#91;</span>CCTexture2D setDefaultAlphaPixelFormat<span style="color: #002200;">:</span>kTexture2DPixelFormat_RGBA4444<span style="color: #002200;">&#93;</span>;
<span style="color: #11740a; font-style: italic;">// Available textures </span>
<span style="color: #11740a; font-style: italic;">// kCCTexture2DPixelFormat_RGBA8888 - 32-bit texture with Alpha channel</span>
<span style="color: #11740a; font-style: italic;">// kCCTexture2DPixelFormat_RGB565 - 16-bit texture without Alpha channel</span>
<span style="color: #11740a; font-style: italic;">// kCCTexture2DPixelFormat_A8 - 8-bit textures used as masks</span>
<span style="color: #11740a; font-style: italic;">// kCCTexture2DPixelFormat_I8 - 8-bit intensity texture</span>
<span style="color: #11740a; font-style: italic;">// kCCTexture2DPixelFormat_AI88 - 16-bit textures used as masks</span>
<span style="color: #11740a; font-style: italic;">// kCCTexture2DPixelFormat_RGBA4444 - 16-bit textures: RGBA4444</span>
<span style="color: #11740a; font-style: italic;">// kCCTexture2DPixelFormat_RGB5A1 - 16-bit textures: RGB5A1</span>
<span style="color: #11740a; font-style: italic;">// kCCTexture2DPixelFormat_PVRTC4 - 4-bit PVRTC-compressed texture: PVRTC4</span>
<span style="color: #11740a; font-style: italic;">// kCCTexture2DPixelFormat_PVRTC2 - 2-bit PVRTC-compressed texture: PVRTC2</span></pre></div></div>

<p>Using a PVRTC will give you better performance and faster loading times, but worse quality and more disk space. Well, I guess you&#8217;ll have to pick the lesser of the two evils <img src='http://www.uchidacoonga.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  You can always mix PNGs and PVRTCs, so that is another option. It is definitely a balancing act.</p>
<h4><span style="color: #ff6600;"><strong>Tools of the Trade</strong></span></h4>
<p>So, how exactly do you create a PVRTC texture from a PNG? There are a few tools available. </p>
<ul>
<li>
<a href="http://www.texturepacker.com/">TexturePacker</a> allows you create sprite sheets with an option for saving the textures as a PVRTC. </li>
<li><a href="http://developer.apple.com/library/ios/#documentation/3DDrawing/Conceptual/OpenGLES_ProgrammingGuide/TextureTool/TextureTool.html">TextureTool</a> is a tool in the iOS SDK that allows you to compress your textures into a PVR texture format.</li>
<li><a href="http://www.imgtec.com/powervr/insider/powervr-pvrtextool.asp">PVRTexTool</a> is the one I use. It is a free tool which comes with both a GUI and a command line utility.</li>
</ul>
<p>I can&#8217;t speak for TexturePacker because I haven&#8217;t used it before, but with the other two,  you will have to tinker with it to have it generate the correct textures. Let me save you the frustration and give you a simple PVRTexTool command-line command that I use to convert my <a href="http://zwoptexapp.com/">Zwoptex</a> created texture atlas from a PNG to a PVR.</p>
<p><em>PVRTexTool -fOGLPVRTC4 -iMyAtlas.png -yflip0 -premultalpha -pvrtiterations8</em></p>
<p>The command above will create a PVRTC4BPP texture which will be saved as MyAtlas.pvr. If you are curious about what all the options mean, then take a look at the manual that comes with PVRTexTool, which has detailed information about them.</p>
<h4><span style="color: #ff6600;"><strong>How to Load it Using Cocos2d</strong></span></h4>
<p>This part is pretty trivial. Here is the code to load the PVRTC texture in Cocos2d. I&#8217;m assuming that you are loading a sprite atlas.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;">CCTexture2D <span style="color: #002200;">*</span>tex <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>CCTextureCache sharedTextureCache<span style="color: #002200;">&#93;</span> addImage<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;MyAtlas.pvr&quot;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>CCSpriteFrameCache sharedSpriteFrameCache<span style="color: #002200;">&#93;</span> addSpriteFramesWithFile<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;MyAtlas.plist&quot;</span> texture<span style="color: #002200;">:</span>tex<span style="color: #002200;">&#93;</span>;</pre></div></div>

<p>I hope this has been helpful. And for those in the United States, happy 4th of July! I live near Washington D.C., but I am not courageous enough to brave the traffic to go see the fireworks <img src='http://www.uchidacoonga.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  I-66 will do that to you (if you live around here, you&#8217;ll know what I mean!).</p>

<p><a href="http://feedads.g.doubleclick.net/~a/qEu-8OlYqyvUhoIn9HNK9shEOhI/0/da"><img src="http://feedads.g.doubleclick.net/~a/qEu-8OlYqyvUhoIn9HNK9shEOhI/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/qEu-8OlYqyvUhoIn9HNK9shEOhI/1/da"><img src="http://feedads.g.doubleclick.net/~a/qEu-8OlYqyvUhoIn9HNK9shEOhI/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.uchidacoonga.com/2011/07/pvrtc-textures-and-cocos2d/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Simple Platformer Using Cocos2d and Box2d with Collision Detection</title>
		<link>http://www.uchidacoonga.com/2011/03/simple-platformer-using-cocos2d-and-box2d-with-collision-detection/</link>
		<comments>http://www.uchidacoonga.com/2011/03/simple-platformer-using-cocos2d-and-box2d-with-collision-detection/#comments</comments>
		<pubDate>Fri, 18 Mar 2011 02:02:56 +0000</pubDate>
		<dc:creator>Min</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[iPhone Development]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Box2D]]></category>
		<category><![CDATA[Cocos2D]]></category>

		<guid isPermaLink="false">http://www.uchidacoonga.com/?p=1056</guid>
		<description><![CDATA[I received a few requests for a simple Mario-like platformer tutorial. So I am keeping my promise. The sample is far from a full fledged Mario clone, but I hope it it can at least start you off in the right direction. This tutorial builds upon concepts covered in &#8220;Beginning Box2d Physics Engine&#8221; and &#8220;Side <a href='http://www.uchidacoonga.com/2011/03/simple-platformer-using-cocos2d-and-box2d-with-collision-detection/'>... [READ THE FULL ARTICLE]</a>]]></description>
			<content:encoded><![CDATA[<p>I received a few requests for a simple Mario-like platformer tutorial. So I am keeping my promise. The sample is far from a full fledged Mario clone, but I hope it it can at least start you off in the right direction.  This tutorial builds upon concepts covered in <a href="http://www.uchidacoonga.com/2011/01/lesson-1-beginning-box2d-physics-engine/">&#8220;Beginning Box2d Physics Engine&#8221;</a> and <a href="http://www.uchidacoonga.com/2011/01/side-scrolling-the-background-in-box2d/">&#8220;Side Scrolling the Background in Box2d and Cocos2d&#8221;</a>, so I suggest reading them first. </p>
<h4><span style="color: #ff6600;"><strong>What&#8217;s Covered?</strong></span></h4>
<p>I will be covering the following topics in this tutorial.</p>
<ul>
<li>Simple object oriented game design</li>
<li>User input / touch detection</li>
<li>Applying forces to game objects to make it move and jump</li>
<li>Collision detection</li>
</ul>
<h4><span style="color: #ff6600;"><strong>Simple Object Oriented Game Design</strong></span></h4>
<p>The example app will be a very rudimentary platformer, with some platforms and the player represented by a circle. Again, I am creating the physics world by reading in the tile map designed in the program Tiled as described in my previous tutorial. The newest version of Tiled at the time of this writing is 0.6.0, and you must go into preferences and set gzip as the default compression or Cocos2d will fail to load the tile map file. The player will be able to move to the right (moving to the left is left to the reader as an exercise) and jump. The app has only two objects. The first is the player object and the other is the platform object. Both the player and the platform object will inherit from the general GameObject class. The general GameObject class inherits from Cocos2d&#8217;s CCSprite object and has a property called &#8220;type&#8221; which is used to distinguish between a player and a platform. Having our objects inherit from the same parent object (GameObject) will make it easier to identify objects when we handle collision detection. </p>
<p>Here is the code for the GameObject class. Notice that it inherits from CCSprite and that we initialize the default type to kGameObjectNone (there is an enum defined in Constants.h, which is not shown here but will be included in the sample source).</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// GameObject.h</span>
<span style="color: #6e371a;">#import &quot;cocos2d.h&quot;</span>
<span style="color: #6e371a;">#import &quot;Constants.h&quot;</span>
&nbsp;
<span style="color: #a61390;">@interface</span> GameObject <span style="color: #002200;">:</span> CCSprite <span style="color: #002200;">&#123;</span>
    GameObjectType  type;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #a61390;">@property</span> <span style="color: #002200;">&#40;</span>nonatomic, readwrite<span style="color: #002200;">&#41;</span> GameObjectType type;
<span style="color: #a61390;">@end</span>
&nbsp;
<span style="color: #11740a; font-style: italic;">////////////////////////////////////////////////////////</span>
&nbsp;
<span style="color: #11740a; font-style: italic;">// GameObject.m</span>
<span style="color: #a61390;">@implementation</span> GameObject
<span style="color: #a61390;">@synthesize</span> type;
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>init
<span style="color: #002200;">&#123;</span>
    self <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>super init<span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>self<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        type <span style="color: #002200;">=</span> kGameObjectNone;
    <span style="color: #002200;">&#125;</span>
&nbsp;
    <span style="color: #a61390;">return</span> self;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>dealloc
<span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>super dealloc<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
<span style="color: #a61390;">@end</span></pre></div></div>

<p>The next one shown is the Player class. Note that the extension for the Player class is Player.mm (two m&#8217;s). Do you see the Box2d&#8217;s b2Body object that is declared? Box2d is written in C++ not Objective-C, so this is the reason we must make the Player class support both Objective-C and C++ by naming the extension with two m&#8217;s. With only one, you will see a lot of errors during compilation. You can see that the type is set to kGameObjectPlayer. You will see the &#8220;type&#8221; come into play when we discuss collision detection later.</p>
<p>The Player class will be in charge of creating the Box2d physics object and adding itself into the physics world when the createBox2dObject method is called. We set the custom user data (playerBodyDef.userData) to &#8220;self&#8221; so that we can access the Cocos2d object from the Box2d&#8217;s contact listener. It also has methods to make the Player move to the right and jump, which will also be discussed later in the tutorial.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// Player.h</span>
<span style="color: #6e371a;">#import &quot;cocos2d.h&quot;</span>
<span style="color: #6e371a;">#import &quot;Box2D.h&quot;</span>
<span style="color: #6e371a;">#import &quot;GameObject.h&quot;</span>
&nbsp;
<span style="color: #a61390;">@interface</span> Player <span style="color: #002200;">:</span> GameObject <span style="color: #002200;">&#123;</span>
    b2Body          <span style="color: #002200;">*</span>body;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> createBox2dObject<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>b2World<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>world;
<span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> jump;
<span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> moveRight;
&nbsp;
<span style="color: #a61390;">@property</span> <span style="color: #002200;">&#40;</span>nonatomic, readwrite<span style="color: #002200;">&#41;</span> b2Body <span style="color: #002200;">*</span>body;
<span style="color: #a61390;">@end</span>
&nbsp;
<span style="color: #11740a; font-style: italic;">///////////////////////////////////////////////////////</span>
&nbsp;
<span style="color: #11740a; font-style: italic;">// Player.mm</span>
<span style="color: #6e371a;">#import &quot;Player.h&quot;</span>
<span style="color: #6e371a;">#import &quot;Constants.h&quot;</span>
&nbsp;
<span style="color: #a61390;">@implementation</span> Player
<span style="color: #a61390;">@synthesize</span> body;
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span> init <span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#40;</span>self <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>super init<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
		type <span style="color: #002200;">=</span> kGameObjectPlayer;
	<span style="color: #002200;">&#125;</span>
	<span style="color: #a61390;">return</span> self;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> createBox2dObject<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>b2World<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>world <span style="color: #002200;">&#123;</span>
    b2BodyDef playerBodyDef;
	playerBodyDef.type <span style="color: #002200;">=</span> b2_dynamicBody;
	playerBodyDef.position.Set<span style="color: #002200;">&#40;</span>self.position.x<span style="color: #002200;">/</span>PTM_RATIO, self.position.y<span style="color: #002200;">/</span>PTM_RATIO<span style="color: #002200;">&#41;</span>;
	playerBodyDef.userData <span style="color: #002200;">=</span> self;
	playerBodyDef.fixedRotation <span style="color: #002200;">=</span> <span style="color: #a61390;">true</span>;
&nbsp;
	body <span style="color: #002200;">=</span> world<span style="color: #002200;">-</span>&gt;CreateBody<span style="color: #002200;">&#40;</span><span style="color: #002200;">&amp;</span>playerBodyDef<span style="color: #002200;">&#41;</span>;
&nbsp;
	b2CircleShape circleShape;
	circleShape.m_radius <span style="color: #002200;">=</span> <span style="color: #2400d9;">0.7</span>;
	b2FixtureDef fixtureDef;
	fixtureDef.shape <span style="color: #002200;">=</span> <span style="color: #002200;">&amp;</span>circleShape;
	fixtureDef.density <span style="color: #002200;">=</span> 1.0f;
	fixtureDef.friction <span style="color: #002200;">=</span> 1.0f;
	fixtureDef.restitution <span style="color: #002200;">=</span>  0.0f;
	body<span style="color: #002200;">-</span>&gt;CreateFixture<span style="color: #002200;">&#40;</span><span style="color: #002200;">&amp;</span>fixtureDef<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> moveRight <span style="color: #002200;">&#123;</span>
    b2Vec2 impulse <span style="color: #002200;">=</span> b2Vec2<span style="color: #002200;">&#40;</span>7.0f, 0.0f<span style="color: #002200;">&#41;</span>;
    body<span style="color: #002200;">-</span>&gt;ApplyLinearImpulse<span style="color: #002200;">&#40;</span>impulse, body<span style="color: #002200;">-</span>&gt;GetWorldCenter<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;		
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> jump <span style="color: #002200;">&#123;</span>
    b2Vec2 impulse <span style="color: #002200;">=</span> b2Vec2<span style="color: #002200;">&#40;</span>4.0f, 15.0f<span style="color: #002200;">&#41;</span>;
    body<span style="color: #002200;">-</span>&gt;ApplyLinearImpulse<span style="color: #002200;">&#40;</span>impulse, body<span style="color: #002200;">-</span>&gt;GetWorldCenter<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;		    
<span style="color: #002200;">&#125;</span>
<span style="color: #a61390;">@end</span></pre></div></div>

<p>As for the platform object, there isn&#8217;t a specific Platform object. For convenience, we simply allocate a GameObject object and specifically set the type to kGameObjectPlatform (see makeBox2dObjectAt method in GameScene way below). </p>
<h4><span style="color: #ff6600;"><strong>User Input / Touch Detection</strong></span></h4>
<p>The following two lines inside GameScene&#8217;s init method are responsible for enabling the touch input.  The swallowsTouches argument on line 3 says that whatever touches that GameScene receives is &#8220;swallowed&#8221; or ends in GameScene and is not further propagated.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// Inside GameScene's init method</span>
self.isTouchEnabled <span style="color: #002200;">=</span> <span style="color: #a61390;">YES</span>;
<span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>CCTouchDispatcher sharedDispatcher<span style="color: #002200;">&#93;</span> addTargetedDelegate<span style="color: #002200;">:</span>self priority<span style="color: #002200;">:</span><span style="color: #2400d9;">0</span> swallowsTouches<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p>The method below is called when the mouse is clicked in the simulator or the screen is touched on the device. We get the location of the touch, and if the touch is on the left half of the screen, we move the player to the right. If the touch is on the right half of the screen, we make the player jump. We are not using it in this tutorial, but if you need it, then there is also a complimentary method to detect when the touch has ended. Note that this code is for a single touch, not multi-touches.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// GameScene.mm</span>
<span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">BOOL</span><span style="color: #002200;">&#41;</span> ccTouchBegan<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UITouch <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>touch withEvent<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIEvent <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>event <span style="color: #002200;">&#123;</span>    
    CGPoint location <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>touch locationInView<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>touch view<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
    location <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>CCDirector sharedDirector<span style="color: #002200;">&#93;</span> convertToGL<span style="color: #002200;">:</span>location<span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>location.x &lt;<span style="color: #002200;">=</span> screenSize.width <span style="color: #002200;">/</span> <span style="color: #2400d9;">2</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        <span style="color: #002200;">&#91;</span>player moveRight<span style="color: #002200;">&#93;</span>;        
    <span style="color: #002200;">&#125;</span> <span style="color: #a61390;">else</span> <span style="color: #002200;">&#123;</span>
        <span style="color: #002200;">&#91;</span>player jump<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>
    <span style="color: #a61390;">return</span> TRUE;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> ccTouchEnded<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UITouch <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>touch withEvent<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIEvent <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>event <span style="color: #002200;">&#123;</span>
    CCLOG<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Touch ended&quot;</span><span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre></div></div>

<h4><span style="color: #ff6600;"><strong>Applying Forces to Game Objects to Make it Move and Jump</strong></span></h4>
<p>To make the player move and jump, we apply a force to the player object. Recall that the Player class has the createBox2dObject method which should be called to add a physics object representing the player into the physics world. To move the player to the right, we simply tell Box2d to apply a positive &#8216;x&#8217; force to the physics object that represents the player. And to make it jump, we apply a positive &#8216;x&#8217; force along with a positive &#8216;y&#8217; force to the physics object. In this case, we are applying an impulse force (it&#8217;s a sudden burst of force) but you are not limited to it (please see the Box2d manual for information on other kind of forces). All the rest is handled by the Box2d physics engine. Once the force has been applied, we update the player&#8217;s position in the main game loop with the new position provided to us by the physics engine (see the complete GameScene source further down, inside the update method).</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> moveRight <span style="color: #002200;">&#123;</span>
    b2Vec2 impulse <span style="color: #002200;">=</span> b2Vec2<span style="color: #002200;">&#40;</span>7.0f, 0.0f<span style="color: #002200;">&#41;</span>;
    body<span style="color: #002200;">-</span>&gt;ApplyLinearImpulse<span style="color: #002200;">&#40;</span>impulse, body<span style="color: #002200;">-</span>&gt;GetWorldCenter<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;		
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> jump <span style="color: #002200;">&#123;</span>
    b2Vec2 impulse <span style="color: #002200;">=</span> b2Vec2<span style="color: #002200;">&#40;</span>4.0f, 15.0f<span style="color: #002200;">&#41;</span>;
    body<span style="color: #002200;">-</span>&gt;ApplyLinearImpulse<span style="color: #002200;">&#40;</span>impulse, body<span style="color: #002200;">-</span>&gt;GetWorldCenter<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;		    
<span style="color: #002200;">&#125;</span></pre></div></div>

<h4><span style="color: #ff6600;"><strong>Collision Detection</strong></span></h4>
<p>For our simple example, only two objects exist in the world (player and platform). In order to detect when the player has made contact with the platform and when the player has lost contact with the platform, we must set up a contact listener and tell Box2d to use said contact listener. The contact listener is a C++ class which inherits from Box2d&#8217;s b2ContactListener class. </p>
<p>The two functions that we are most interested in are BeginContact and EndContact. As the function name suggests, BeginContact is called whenever two objects in the world make contact with each other. And EndContact is called as soon as the contact is broken.  You see that a b2Contact object is passed to the functions, which can be used to get the user data. The b2Contact object has two function calls GetFixtureA() and GetFixtureB() which can be used to return the two Box2d bodies involved in the collision, and subsequently the user data (our GameObject objects) stored in them. Recall that all the objects in our app is inherited from the GameObject class, so we can safely cast the user data for both to GameObjects. Once we have the two GameObjects, we can check the &#8220;type&#8221; property of each of the objects to check whether it is the player or the platform. It is important to remember that no guarantee is made as to which object of the two objects is the player object or the platform object. It is up to us to determine their types, so both objects must be checked to see if it is one or the other.</p>
<p>To help keep the code cleaner and easier to read, there are two macros called IS_PLAYER(x,y) and IS_PLATFORM(x,y) which test whether either one of the the objects is a player or a platform. For this simple example, a simple message is printed to the console when the contact is made or lost. In a real game, you could, for example, play a sound effect when two objects collide. Also, please remember that although it is tempting to implement game logic that alters the physics world inside a contact callback, this is not allowed. The Box2d manual states that&#8230;</p>
<blockquote><p>&#8230;for example, you may have a collision that applies damage and try to destroy the associated actor and its rigid body. However, Box2D does not allow you to alter the physics world inside a callback because you might destroy objects that Box2D is currently processing, leading to orphaned pointers  (<a href="http://www.box2d.org/manual.html">http://www.box2d.org/manual.html</a>)</p></blockquote>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// ContactListener.h</span>
<span style="color: #6e371a;">#import &quot;Box2D.h&quot;</span>
&nbsp;
class ContactListener <span style="color: #002200;">:</span> public b2ContactListener <span style="color: #002200;">&#123;</span>
public<span style="color: #002200;">:</span>
	ContactListener<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
	~ContactListener<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
	virtual <span style="color: #a61390;">void</span> BeginContact<span style="color: #002200;">&#40;</span>b2Contact <span style="color: #002200;">*</span>contact<span style="color: #002200;">&#41;</span>;
	virtual <span style="color: #a61390;">void</span> EndContact<span style="color: #002200;">&#40;</span>b2Contact <span style="color: #002200;">*</span>contact<span style="color: #002200;">&#41;</span>;
	virtual <span style="color: #a61390;">void</span> PreSolve<span style="color: #002200;">&#40;</span>b2Contact <span style="color: #002200;">*</span>contact, <span style="color: #a61390;">const</span> b2Manifold <span style="color: #002200;">*</span>oldManifold<span style="color: #002200;">&#41;</span>;
	virtual <span style="color: #a61390;">void</span> PostSolve<span style="color: #002200;">&#40;</span>b2Contact <span style="color: #002200;">*</span>contact, <span style="color: #a61390;">const</span> b2ContactImpulse <span style="color: #002200;">*</span>impulse<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">/////////////////////////////</span>
&nbsp;
<span style="color: #11740a; font-style: italic;">// ContactListener.mm</span>
<span style="color: #6e371a;">#import &quot;ContactListener.h&quot;</span>
<span style="color: #6e371a;">#import &quot;Constants.h&quot;</span>
<span style="color: #6e371a;">#import &quot;GameObject.h&quot;</span>
&nbsp;
<span style="color: #6e371a;">#define IS_PLAYER(x, y)         (x.type == kGameObjectPlayer || y.type == kGameObjectPlayer)</span>
<span style="color: #6e371a;">#define IS_PLATFORM(x, y)       (x.type == kGameObjectPlatform || y.type == kGameObjectPlatform)</span>
&nbsp;
&nbsp;
ContactListener<span style="color: #002200;">::</span>ContactListener<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
<span style="color: #002200;">&#125;</span>
&nbsp;
ContactListener<span style="color: #002200;">::</span>~ContactListener<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #a61390;">void</span> ContactListener<span style="color: #002200;">::</span>BeginContact<span style="color: #002200;">&#40;</span>b2Contact <span style="color: #002200;">*</span>contact<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
	GameObject <span style="color: #002200;">*</span>o1 <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>GameObject<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>contact<span style="color: #002200;">-</span>&gt;GetFixtureA<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">-</span>&gt;GetBody<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">-</span>&gt;GetUserData<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
	GameObject <span style="color: #002200;">*</span>o2 <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>GameObject<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>contact<span style="color: #002200;">-</span>&gt;GetFixtureB<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">-</span>&gt;GetBody<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">-</span>&gt;GetUserData<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>IS_PLATFORM<span style="color: #002200;">&#40;</span>o1, o2<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&amp;&amp;</span> IS_PLAYER<span style="color: #002200;">&#40;</span>o1, o2<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        CCLOG<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;-----&gt; Player made contact with platform!&quot;</span><span style="color: #002200;">&#41;</span>;
    <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #a61390;">void</span> ContactListener<span style="color: #002200;">::</span>EndContact<span style="color: #002200;">&#40;</span>b2Contact <span style="color: #002200;">*</span>contact<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
	GameObject <span style="color: #002200;">*</span>o1 <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>GameObject<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>contact<span style="color: #002200;">-</span>&gt;GetFixtureA<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">-</span>&gt;GetBody<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">-</span>&gt;GetUserData<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
	GameObject <span style="color: #002200;">*</span>o2 <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>GameObject<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>contact<span style="color: #002200;">-</span>&gt;GetFixtureB<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">-</span>&gt;GetBody<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">-</span>&gt;GetUserData<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>IS_PLATFORM<span style="color: #002200;">&#40;</span>o1, o2<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&amp;&amp;</span> IS_PLAYER<span style="color: #002200;">&#40;</span>o1, o2<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        CCLOG<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;-----&gt; Player lost contact with platform!&quot;</span><span style="color: #002200;">&#41;</span>;
    <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #a61390;">void</span> ContactListener<span style="color: #002200;">::</span>PreSolve<span style="color: #002200;">&#40;</span>b2Contact <span style="color: #002200;">*</span>contact, <span style="color: #a61390;">const</span> b2Manifold <span style="color: #002200;">*</span>oldManifold<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #a61390;">void</span> ContactListener<span style="color: #002200;">::</span>PostSolve<span style="color: #002200;">&#40;</span>b2Contact <span style="color: #002200;">*</span>contact, <span style="color: #a61390;">const</span> b2ContactImpulse <span style="color: #002200;">*</span>impulse<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
<span style="color: #002200;">&#125;</span></pre></div></div>

<p>You then register the contact listener when you set up the physics world.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"> contactListener <span style="color: #002200;">=</span> new ContactListener<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
 world<span style="color: #002200;">-</span>&gt;SetContactListener<span style="color: #002200;">&#40;</span>contactListener<span style="color: #002200;">&#41;</span>;</pre></div></div>

<h4><span style="color: #ff6600;"><strong>Wrap-up and Loose Ends</strong></span></h4>
<p>Below is the code for the GameScene class. If certain things look unfamiliar to you, please refer to the previous two tutorials that I mentioned in the beginning of the article. If you have read those tutorials, then things should be familiar except for the contact listener registration code and the touch detection code, which I have already explained earlier in the tutorial. </p>
<p>You can find the complete source code for download and the demo video at the end of the tutorial.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// GameScene.h</span>
&nbsp;
<span style="color: #6e371a;">#import &quot;cocos2d.h&quot;</span>
<span style="color: #6e371a;">#import &quot;Box2D.h&quot;</span>
<span style="color: #6e371a;">#import &quot;GLES-Render.h&quot;</span>
<span style="color: #6e371a;">#import &quot;ContactListener.h&quot;</span>
&nbsp;
<span style="color: #a61390;">@class</span> Player;
&nbsp;
<span style="color: #a61390;">@interface</span> GameScene <span style="color: #002200;">:</span> CCLayer
<span style="color: #002200;">&#123;</span>
    CGSize screenSize;
	b2World<span style="color: #002200;">*</span> world;
	GLESDebugDraw <span style="color: #002200;">*</span>m_debugDraw;
	CCTMXTiledMap <span style="color: #002200;">*</span>tileMapNode;	
    Player <span style="color: #002200;">*</span>player;
    ContactListener <span style="color: #002200;">*</span>contactListener;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">+</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span> scene;
<span style="color: #a61390;">@end</span>
&nbsp;
<span style="color: #11740a; font-style: italic;">///////////////////////////////////////////////</span>
&nbsp;
<span style="color: #11740a; font-style: italic;">// GameScene.mm</span>
<span style="color: #6e371a;">#import &quot;GameScene.h&quot;</span>
<span style="color: #6e371a;">#import &quot;Constants.h&quot;</span>
<span style="color: #6e371a;">#import &quot;Player.h&quot;</span>
<span style="color: #6e371a;">#import &quot;GameObject.h&quot;</span>
&nbsp;
<span style="color: #a61390;">@interface</span> GameScene<span style="color: #002200;">&#40;</span>Private<span style="color: #002200;">&#41;</span> 
<span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> setupPhysicsWorld;
<span style="color: #a61390;">@end</span>
&nbsp;
<span style="color: #a61390;">@implementation</span> GameScene
&nbsp;
<span style="color: #002200;">+</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span> scene
<span style="color: #002200;">&#123;</span>
	<span style="color: #11740a; font-style: italic;">// 'scene' is an autorelease object.</span>
	CCScene <span style="color: #002200;">*</span>scene <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>CCScene node<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// 'layer' is an autorelease object.</span>
	GameScene <span style="color: #002200;">*</span>layer <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>GameScene node<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// add layer as a child to scene</span>
	<span style="color: #002200;">&#91;</span>scene addChild<span style="color: #002200;">:</span> layer<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// return the scene</span>
	<span style="color: #a61390;">return</span> scene;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> makeBox2dObjAt<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CGPoint<span style="color: #002200;">&#41;</span>p 
			   withSize<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CGPoint<span style="color: #002200;">&#41;</span>size 
				dynamic<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">BOOL</span><span style="color: #002200;">&#41;</span>d 
			   rotation<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">long</span><span style="color: #002200;">&#41;</span>r 
			   friction<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">long</span><span style="color: #002200;">&#41;</span>f 
				density<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">long</span><span style="color: #002200;">&#41;</span>dens 
			restitution<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">long</span><span style="color: #002200;">&#41;</span>rest 
				  boxId<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">int</span><span style="color: #002200;">&#41;</span>boxId <span style="color: #002200;">&#123;</span>
&nbsp;
	<span style="color: #11740a; font-style: italic;">// Define the dynamic body.</span>
	<span style="color: #11740a; font-style: italic;">//Set up a 1m squared box in the physics world</span>
	b2BodyDef bodyDef;
<span style="color: #11740a; font-style: italic;">//	bodyDef.angle = r;</span>
&nbsp;
	<span style="color: #a61390;">if</span><span style="color: #002200;">&#40;</span>d<span style="color: #002200;">&#41;</span>
		bodyDef.type <span style="color: #002200;">=</span> b2_dynamicBody;
&nbsp;
	bodyDef.position.Set<span style="color: #002200;">&#40;</span>p.x<span style="color: #002200;">/</span>PTM_RATIO, p.y<span style="color: #002200;">/</span>PTM_RATIO<span style="color: #002200;">&#41;</span>;
&nbsp;
    GameObject <span style="color: #002200;">*</span>platform <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>GameObject alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>platform setType<span style="color: #002200;">:</span>kGameObjectPlatform<span style="color: #002200;">&#93;</span>;
	bodyDef.userData <span style="color: #002200;">=</span> platform;
&nbsp;
	b2Body <span style="color: #002200;">*</span>body <span style="color: #002200;">=</span> world<span style="color: #002200;">-</span>&gt;CreateBody<span style="color: #002200;">&#40;</span><span style="color: #002200;">&amp;</span>bodyDef<span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// Define another box shape for our dynamic body.</span>
	b2PolygonShape dynamicBox;
	dynamicBox.SetAsBox<span style="color: #002200;">&#40;</span>size.x<span style="color: #002200;">/</span><span style="color: #2400d9;">2</span><span style="color: #002200;">/</span>PTM_RATIO, size.y<span style="color: #002200;">/</span><span style="color: #2400d9;">2</span><span style="color: #002200;">/</span>PTM_RATIO<span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// Define the dynamic body fixture.</span>
	b2FixtureDef fixtureDef;
	fixtureDef.shape <span style="color: #002200;">=</span> <span style="color: #002200;">&amp;</span>dynamicBox;	
	fixtureDef.density <span style="color: #002200;">=</span> dens;
	fixtureDef.friction <span style="color: #002200;">=</span> f;
	fixtureDef.restitution <span style="color: #002200;">=</span> rest;
	body<span style="color: #002200;">-</span>&gt;CreateFixture<span style="color: #002200;">&#40;</span><span style="color: #002200;">&amp;</span>fixtureDef<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
&nbsp;
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> drawCollisionTiles <span style="color: #002200;">&#123;</span>
	CCTMXObjectGroup <span style="color: #002200;">*</span>objects <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>tileMapNode objectGroupNamed<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Collision&quot;</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #400080;">NSMutableDictionary</span> <span style="color: #002200;">*</span> objPoint;
&nbsp;
	<span style="color: #a61390;">int</span> x, y, w, h;	
	<span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span>objPoint <span style="color: #a61390;">in</span> <span style="color: #002200;">&#91;</span>objects objects<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
		x <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>objPoint valueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;x&quot;</span><span style="color: #002200;">&#93;</span> intValue<span style="color: #002200;">&#93;</span>;
		y <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>objPoint valueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;y&quot;</span><span style="color: #002200;">&#93;</span> intValue<span style="color: #002200;">&#93;</span>;
		w <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>objPoint valueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;width&quot;</span><span style="color: #002200;">&#93;</span> intValue<span style="color: #002200;">&#93;</span>;
		h <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>objPoint valueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;height&quot;</span><span style="color: #002200;">&#93;</span> intValue<span style="color: #002200;">&#93;</span>;	
&nbsp;
		CGPoint _point<span style="color: #002200;">=</span>ccp<span style="color: #002200;">&#40;</span>x<span style="color: #002200;">+</span>w<span style="color: #002200;">/</span><span style="color: #2400d9;">2</span>,y<span style="color: #002200;">+</span>h<span style="color: #002200;">/</span><span style="color: #2400d9;">2</span><span style="color: #002200;">&#41;</span>;
		CGPoint _size<span style="color: #002200;">=</span>ccp<span style="color: #002200;">&#40;</span>w,h<span style="color: #002200;">&#41;</span>;
&nbsp;
		<span style="color: #002200;">&#91;</span>self makeBox2dObjAt<span style="color: #002200;">:</span>_point 
					withSize<span style="color: #002200;">:</span>_size 
					 dynamic<span style="color: #002200;">:</span><span style="color: #a61390;">false</span> 
					rotation<span style="color: #002200;">:</span><span style="color: #2400d9;">0</span> 
					friction<span style="color: #002200;">:</span>1.5f 
					 density<span style="color: #002200;">:</span>0.0f 
				 restitution<span style="color: #002200;">:</span><span style="color: #2400d9;">0</span> 
					   boxId<span style="color: #002200;">:-</span><span style="color: #2400d9;">1</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> addScrollingBackgroundWithTileMap <span style="color: #002200;">&#123;</span>
	tileMapNode <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>CCTMXTiledMap tiledMapWithTMXFile<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;scroller.tmx&quot;</span><span style="color: #002200;">&#93;</span>;
	tileMapNode.anchorPoint <span style="color: #002200;">=</span> ccp<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">0</span>, <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>;
	<span style="color: #002200;">&#91;</span>self addChild<span style="color: #002200;">:</span>tileMapNode<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
&nbsp;
<span style="color: #11740a; font-style: italic;">// initialize your instance here</span>
<span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span> init
<span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">if</span><span style="color: #002200;">&#40;</span> <span style="color: #002200;">&#40;</span>self<span style="color: #002200;">=</span><span style="color: #002200;">&#91;</span>super init<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
&nbsp;
		<span style="color: #11740a; font-style: italic;">// enable touches</span>
		self.isTouchEnabled <span style="color: #002200;">=</span> <span style="color: #a61390;">YES</span>;
&nbsp;
		screenSize <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>CCDirector sharedDirector<span style="color: #002200;">&#93;</span>.winSize;
		<span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>CCTouchDispatcher sharedDispatcher<span style="color: #002200;">&#93;</span> addTargetedDelegate<span style="color: #002200;">:</span>self priority<span style="color: #002200;">:</span><span style="color: #2400d9;">0</span> swallowsTouches<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;   
&nbsp;
		<span style="color: #002200;">&#91;</span>self setupPhysicsWorld<span style="color: #002200;">&#93;</span>;
&nbsp;
		<span style="color: #002200;">&#91;</span>self addScrollingBackgroundWithTileMap<span style="color: #002200;">&#93;</span>;
		<span style="color: #002200;">&#91;</span>self drawCollisionTiles<span style="color: #002200;">&#93;</span>;
&nbsp;
		player <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>Player spriteWithFile<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Icon-Small.png&quot;</span><span style="color: #002200;">&#93;</span>;        
		player.position <span style="color: #002200;">=</span> ccp<span style="color: #002200;">&#40;</span>100.0f, 180.0f<span style="color: #002200;">&#41;</span>;
		<span style="color: #002200;">&#91;</span>player createBox2dObject<span style="color: #002200;">:</span>world<span style="color: #002200;">&#93;</span>;
&nbsp;
		<span style="color: #002200;">&#91;</span>self addChild<span style="color: #002200;">:</span>player<span style="color: #002200;">&#93;</span>;
&nbsp;
        <span style="color: #11740a; font-style: italic;">// Start main game loop</span>
		<span style="color: #002200;">&#91;</span>self scheduleUpdate<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#125;</span>
	<span style="color: #a61390;">return</span> self;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> setupPhysicsWorld <span style="color: #002200;">&#123;</span>
    b2Vec2 gravity <span style="color: #002200;">=</span> b2Vec2<span style="color: #002200;">&#40;</span>0.0f, <span style="color: #002200;">-</span>9.8f<span style="color: #002200;">&#41;</span>;
    bool doSleep <span style="color: #002200;">=</span> <span style="color: #a61390;">true</span>;
    world <span style="color: #002200;">=</span> new b2World<span style="color: #002200;">&#40;</span>gravity, doSleep<span style="color: #002200;">&#41;</span>;
&nbsp;
    m_debugDraw <span style="color: #002200;">=</span> new GLESDebugDraw<span style="color: #002200;">&#40;</span>PTM_RATIO<span style="color: #002200;">&#41;</span>;
    world<span style="color: #002200;">-</span>&gt;SetDebugDraw<span style="color: #002200;">&#40;</span>m_debugDraw<span style="color: #002200;">&#41;</span>;
    uint32 flags <span style="color: #002200;">=</span> <span style="color: #2400d9;">0</span>;
    flags <span style="color: #002200;">+=</span> b2DebugDraw<span style="color: #002200;">::</span>e_shapeBit;
    m_debugDraw<span style="color: #002200;">-</span>&gt;SetFlags<span style="color: #002200;">&#40;</span>flags<span style="color: #002200;">&#41;</span>;
&nbsp;
    contactListener <span style="color: #002200;">=</span> new ContactListener<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
    world<span style="color: #002200;">-</span>&gt;SetContactListener<span style="color: #002200;">&#40;</span>contactListener<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> draw <span style="color: #002200;">&#123;</span>
	glDisable<span style="color: #002200;">&#40;</span>GL_TEXTURE_2D<span style="color: #002200;">&#41;</span>;
	glDisableClientState<span style="color: #002200;">&#40;</span>GL_COLOR_ARRAY<span style="color: #002200;">&#41;</span>;
	glDisableClientState<span style="color: #002200;">&#40;</span>GL_TEXTURE_COORD_ARRAY<span style="color: #002200;">&#41;</span>;
&nbsp;
	world<span style="color: #002200;">-</span>&gt;DrawDebugData<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// restore default GL states</span>
	glEnable<span style="color: #002200;">&#40;</span>GL_TEXTURE_2D<span style="color: #002200;">&#41;</span>;
	glEnableClientState<span style="color: #002200;">&#40;</span>GL_COLOR_ARRAY<span style="color: #002200;">&#41;</span>;
	glEnableClientState<span style="color: #002200;">&#40;</span>GL_TEXTURE_COORD_ARRAY<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> update<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>ccTime<span style="color: #002200;">&#41;</span>dt <span style="color: #002200;">&#123;</span>
	<span style="color: #11740a; font-style: italic;">//It is recommended that a fixed time step is used with Box2D for stability</span>
	<span style="color: #11740a; font-style: italic;">//of the simulation, however, we are using a variable time step here.</span>
	<span style="color: #11740a; font-style: italic;">//You need to make an informed choice, the following URL is useful</span>
	<span style="color: #11740a; font-style: italic;">//http://gafferongames.com/game-physics/fix-your-timestep/</span>
&nbsp;
	int32 velocityIterations <span style="color: #002200;">=</span> <span style="color: #2400d9;">8</span>;
	int32 positionIterations <span style="color: #002200;">=</span> <span style="color: #2400d9;">1</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// Instruct the world to perform a single step of simulation. It is</span>
	<span style="color: #11740a; font-style: italic;">// generally best to keep the time step and iterations fixed.</span>
	world<span style="color: #002200;">-</span>&gt;Step<span style="color: #002200;">&#40;</span>dt, velocityIterations, positionIterations<span style="color: #002200;">&#41;</span>;
&nbsp;
&nbsp;
	<span style="color: #11740a; font-style: italic;">//Iterate over the bodies in the physics world</span>
	<span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span>b2Body<span style="color: #002200;">*</span> b <span style="color: #002200;">=</span> world<span style="color: #002200;">-</span>&gt;GetBodyList<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>; b; b <span style="color: #002200;">=</span> b<span style="color: #002200;">-</span>&gt;GetNext<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
		<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>b<span style="color: #002200;">-</span>&gt;GetUserData<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">!=</span> <span style="color: #a61390;">NULL</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
			<span style="color: #11740a; font-style: italic;">//Synchronize the AtlasSprites position and rotation with the corresponding body</span>
			CCSprite <span style="color: #002200;">*</span>myActor <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>CCSprite<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>b<span style="color: #002200;">-</span>&gt;GetUserData<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
			myActor.position <span style="color: #002200;">=</span> CGPointMake<span style="color: #002200;">&#40;</span> b<span style="color: #002200;">-</span>&gt;GetPosition<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>.x <span style="color: #002200;">*</span> PTM_RATIO, 
							b<span style="color: #002200;">-</span>&gt;GetPosition<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>.y <span style="color: #002200;">*</span> PTM_RATIO<span style="color: #002200;">&#41;</span>;
			myActor.rotation <span style="color: #002200;">=</span> <span style="color: #002200;">-</span><span style="color: #2400d9;">1</span> <span style="color: #002200;">*</span> CC_RADIANS_TO_DEGREES<span style="color: #002200;">&#40;</span>b<span style="color: #002200;">-</span>&gt;GetAngle<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;
		<span style="color: #002200;">&#125;</span>	
	<span style="color: #002200;">&#125;</span>	
&nbsp;
	b2Vec2 pos <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>player body<span style="color: #002200;">&#93;</span><span style="color: #002200;">-</span>&gt;GetPosition<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
	CGPoint newPos <span style="color: #002200;">=</span> ccp<span style="color: #002200;">&#40;</span><span style="color: #002200;">-</span><span style="color: #2400d9;">1</span> <span style="color: #002200;">*</span> pos.x <span style="color: #002200;">*</span> PTM_RATIO <span style="color: #002200;">+</span> <span style="color: #2400d9;">50</span>, self.position.y <span style="color: #002200;">*</span> PTM_RATIO<span style="color: #002200;">&#41;</span>;	
	<span style="color: #002200;">&#91;</span>self setPosition<span style="color: #002200;">:</span>newPos<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">BOOL</span><span style="color: #002200;">&#41;</span> ccTouchBegan<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UITouch <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>touch withEvent<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIEvent <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>event <span style="color: #002200;">&#123;</span>    
    CGPoint location <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>touch locationInView<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>touch view<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
    location <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>CCDirector sharedDirector<span style="color: #002200;">&#93;</span> convertToGL<span style="color: #002200;">:</span>location<span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>location.x &lt;<span style="color: #002200;">=</span> screenSize.width <span style="color: #002200;">/</span> <span style="color: #2400d9;">2</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        <span style="color: #002200;">&#91;</span>player moveRight<span style="color: #002200;">&#93;</span>;        
    <span style="color: #002200;">&#125;</span> <span style="color: #a61390;">else</span> <span style="color: #002200;">&#123;</span>
        <span style="color: #002200;">&#91;</span>player jump<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>
	<span style="color: #a61390;">return</span> TRUE;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #11740a; font-style: italic;">// on &quot;dealloc&quot; you need to release all your retained objects</span>
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> dealloc <span style="color: #002200;">&#123;</span>
    <span style="color: #11740a; font-style: italic;">// in case you have something to dealloc, do it in this method</span>
&nbsp;
    delete contactListener;
    delete world;
    world <span style="color: #002200;">=</span> <span style="color: #a61390;">NULL</span>;
&nbsp;
    delete m_debugDraw;
&nbsp;
    <span style="color: #11740a; font-style: italic;">// don't forget to call &quot;super dealloc&quot;</span>
    <span style="color: #002200;">&#91;</span>super dealloc<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
<span style="color: #a61390;">@end</span></pre></div></div>

<p>Demo video of the Simple Platformer in action<br />
<object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/aBufs7MifMI?hl=en&#038;fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/aBufs7MifMI?hl=en&#038;fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object></p>
<p>Download source: <a href="http://www.uchidacoonga.com/SimplePlatformer.zip">SimplePlatformer.zip</a></p>
<p>Happy Saint Patrick&#8217;s Day! I wrote this tutorial while knocking back some Guinness, so I must blame alcohol if you see any glaring mistakes <img src='http://www.uchidacoonga.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>

<p><a href="http://feedads.g.doubleclick.net/~a/kFp9b-rhC3_jUQwPH5tpg7kYWHQ/0/da"><img src="http://feedads.g.doubleclick.net/~a/kFp9b-rhC3_jUQwPH5tpg7kYWHQ/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/kFp9b-rhC3_jUQwPH5tpg7kYWHQ/1/da"><img src="http://feedads.g.doubleclick.net/~a/kFp9b-rhC3_jUQwPH5tpg7kYWHQ/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.uchidacoonga.com/2011/03/simple-platformer-using-cocos2d-and-box2d-with-collision-detection/feed/</wfw:commentRss>
		<slash:comments>56</slash:comments>
		</item>
		<item>
		<title>Easy Way Increase Frame Rate to 60 FPS in Cocos2d</title>
		<link>http://www.uchidacoonga.com/2011/03/increase-frame-rate-to-60-fps-in-cocos2d/</link>
		<comments>http://www.uchidacoonga.com/2011/03/increase-frame-rate-to-60-fps-in-cocos2d/#comments</comments>
		<pubDate>Fri, 11 Mar 2011 16:20:53 +0000</pubDate>
		<dc:creator>Min</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[iPhone Development]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Box2D]]></category>
		<category><![CDATA[Cocos2D]]></category>

		<guid isPermaLink="false">http://www.uchidacoonga.com/?p=1046</guid>
		<description><![CDATA[Life has once again conspired to keep me away from updating the blog as frequently as I promised. I meant to write a simple platformer tutorial, but I had an interview with Google that seriously threw a monkey wrench into my plans. So I am just catching up on the backlog of tasks I need <a href='http://www.uchidacoonga.com/2011/03/increase-frame-rate-to-60-fps-in-cocos2d/'>... [READ THE FULL ARTICLE]</a>]]></description>
			<content:encoded><![CDATA[<p>Life has once again conspired to keep me away from updating the blog as frequently as I promised. I meant to write a simple platformer tutorial, but I had an interview with Google that seriously threw a monkey wrench into my plans. So I am just catching up on the backlog of tasks I need to complete for the game that I am working on, which is shaping up nicely! Hopefully, I will be able to put together a simple tutorial in the near future.</p>
<p>In the meanwhile, here is a very simple change you can make to your game that will instantly increase your frame rate from 30 FPS to 60 FPS especially on the first generation (2G) or the second generation (3G) iPhones. Best of all, the change won&#8217;t take you more than a few seconds to make! Inside GameConfig.h, you will see GAME_AUTOROTATION defined in one of two ways:</p>
<p>The below uses UIViewController and Core Animation to perform the auto rotation:</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#define GAME_AUTOROTATION kGameAutorotationUIViewController</span></pre></div></div>

<p>Or you may see below, which will mean Cocos2d&#8217;s CCDirector will handle the auto rotation:</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#define GAME_AUTOROTATION kGameAutorotationCCDirector</span></pre></div></div>

<p>It is much faster if you let Cocos2d handle the auto rotation because rotation is done by a cheap call to glRotatef() function. This instantly increased my frame rate from 30 FPS to 60 FPS on the 1st generation iPhone.</p>
<p>If you would like more details on why this is, please take a look at the Cocos2d wiki at <a href="http://www.cocos2d-iphone.org/wiki/doku.php/prog_guide:autorotation">http://www.cocos2d-iphone.org/wiki/doku.php/prog_guide:autorotation</a></p>

<p><a href="http://feedads.g.doubleclick.net/~a/wqwLjQD2D3VporRSrdzzObKaTUY/0/da"><img src="http://feedads.g.doubleclick.net/~a/wqwLjQD2D3VporRSrdzzObKaTUY/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/wqwLjQD2D3VporRSrdzzObKaTUY/1/da"><img src="http://feedads.g.doubleclick.net/~a/wqwLjQD2D3VporRSrdzzObKaTUY/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.uchidacoonga.com/2011/03/increase-frame-rate-to-60-fps-in-cocos2d/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Side Scrolling the Background in Box2D and Cocos2D</title>
		<link>http://www.uchidacoonga.com/2011/01/side-scrolling-the-background-in-box2d/</link>
		<comments>http://www.uchidacoonga.com/2011/01/side-scrolling-the-background-in-box2d/#comments</comments>
		<pubDate>Thu, 13 Jan 2011 22:36:32 +0000</pubDate>
		<dc:creator>Min</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[iPhone Development]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Box2D]]></category>
		<category><![CDATA[Cocos2D]]></category>

		<guid isPermaLink="false">http://www.uchidacoonga.com/?p=976</guid>
		<description><![CDATA[I could not find a simple tutorial that demonstrated a Box2D side scroller with the camera fixed on the player. Meaning, it would give the appearance of the background scrolling while the player remains stationary in one spot on the screen. So for this article, I am going go through a simple tutorial to do <a href='http://www.uchidacoonga.com/2011/01/side-scrolling-the-background-in-box2d/'>... [READ THE FULL ARTICLE]</a>]]></description>
			<content:encoded><![CDATA[<p>I could not find a simple tutorial that demonstrated a Box2D side scroller with the camera fixed on the player. Meaning, it would give the appearance of the background scrolling while the player remains stationary in one spot on the screen. So for this article, I am going go through a simple tutorial to do just that. If you are not familiar with the basics of the Box2D physics engine, you may want to check out my previous article <a href="http://www.uchidacoonga.com/2011/01/lesson-1-beginning-box2d-physics-engine/">Beginning Box2D Physics Engine</a>.</p>
<h4><span style="color: #ff6600;"><strong>Video Demo</strong></span></h4>
<p>Here is the video of the demo in action. The circle is the object that the camera should be following. I placed a little Cocos2D sprite in the center just for kicks. Please excuse the choppy video.<br />
<iframe src="http://player.vimeo.com/video/18761454" width="400" height="300" frameborder="0"></iframe>
<p><a href="http://vimeo.com/18761454">Box2D Side Scroller</a> from <a href="http://vimeo.com/user2125614">Min K</a> on <a href="http://vimeo.com">Vimeo</a>.</p>
<h4><span style="color: #ff6600;"><strong>Platform Generation</strong></span></h4>
<p><a href="http://www.uchidacoonga.com/2011/01/side-scrolling-the-background-in-box2d/screen-shot-2011-01-13-at-3-56-29-pm/" rel="attachment wp-att-982"><img src="http://www.uchidacoonga.com/wp-content/uploads/2011/01/Screen-shot-2011-01-13-at-3.56.29-PM-300x211.png" alt="" title="Screen shot 2011-01-13 at 3.56.29 PM" width="300" height="211" class="alignleft size-medium wp-image-982" /></a><br />
For this simple demo, I used the excellent and free software called <a href="http://www.mapeditor.org/">Tiled Map Editor</a> to lay out the scene. You do not have to use the program to draw your scene. You can create the Box2D objects manually. Please check the software&#8217;s web site to learn more about using the software. There really is not much to learn though, because it is very simple to use and understand. The image on the left shows that I have two layers. One layer is the tile layer and the other is actually an object layer, which I titled Collision. I simply drew two boxes in the Collision layer. For this example, the tile layer is actually empty, but you can decide to lay down some actual tile images if you want. Then in the code, I will read the location and size of these collision boxes and create a Box2D object out of them. Here is the code to achieve this.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> addScrollingBackgroundWithTileMap <span style="color: #002200;">&#123;</span>
	tileMapNode <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>CCTMXTiledMap tiledMapWithTMXFile<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;scroller.tmx&quot;</span><span style="color: #002200;">&#93;</span>;
	tileMapNode.anchorPoint <span style="color: #002200;">=</span> ccp<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">0</span>, <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>;
	<span style="color: #002200;">&#91;</span>self addChild<span style="color: #002200;">:</span>tileMapNode<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></div></div>

<p>The code above reads in the tile map with the filename &#8220;scroller.tmx&#8221; that I saved using the application. If you delve into the CCTMXTiledMap source, you will see that the tiles are actually CCSprite objects. But again, for this example, my tile layer is empty because I am only using the object layer which I labeled Collision in Tiled.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> drawCollisionTiles <span style="color: #002200;">&#123;</span>
	CCTMXObjectGroup <span style="color: #002200;">*</span>objects <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>tileMapNode objectGroupNamed<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Collision&quot;</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #400080;">NSMutableDictionary</span> <span style="color: #002200;">*</span> objPoint;
&nbsp;
	<span style="color: #a61390;">int</span> x, y, w, h;	
	<span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span>objPoint <span style="color: #a61390;">in</span> <span style="color: #002200;">&#91;</span>objects objects<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
		x <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>objPoint valueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;x&quot;</span><span style="color: #002200;">&#93;</span> intValue<span style="color: #002200;">&#93;</span>;
		y <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>objPoint valueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;y&quot;</span><span style="color: #002200;">&#93;</span> intValue<span style="color: #002200;">&#93;</span>;
		w <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>objPoint valueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;width&quot;</span><span style="color: #002200;">&#93;</span> intValue<span style="color: #002200;">&#93;</span>;
		h <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>objPoint valueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;height&quot;</span><span style="color: #002200;">&#93;</span> intValue<span style="color: #002200;">&#93;</span>;	
&nbsp;
		CGPoint _point<span style="color: #002200;">=</span>ccp<span style="color: #002200;">&#40;</span>x<span style="color: #002200;">+</span>w<span style="color: #002200;">/</span><span style="color: #2400d9;">2</span>,y<span style="color: #002200;">+</span>h<span style="color: #002200;">/</span><span style="color: #2400d9;">2</span><span style="color: #002200;">&#41;</span>;
		CGPoint _size<span style="color: #002200;">=</span>ccp<span style="color: #002200;">&#40;</span>w,h<span style="color: #002200;">&#41;</span>;
&nbsp;
		<span style="color: #002200;">&#91;</span>self makeBox2dObjAt<span style="color: #002200;">:</span>_point 
					withSize<span style="color: #002200;">:</span>_size 
					 dynamic<span style="color: #002200;">:</span><span style="color: #a61390;">false</span> 
					rotation<span style="color: #002200;">:</span><span style="color: #2400d9;">0</span> 
					friction<span style="color: #002200;">:</span>0.0f 
					 density<span style="color: #002200;">:</span>0.0f 
				 restitution<span style="color: #002200;">:</span><span style="color: #2400d9;">0</span> 
					   boxId<span style="color: #002200;">:-</span><span style="color: #2400d9;">1</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span></pre></div></div>

<p>The drawCollisionTiles method above will read the Collision boxes from the tile map and create Box2D objects out of them. It loops through the node to find all the objects and then uses the location (x, y) and the size (w, h) to create the Box2D object to be placed into the physics world and then simulated. The thing to notice here is that the friction value is set to 0.0. This will cause the circle, which I am using as the player object, to slide across the platform. Had I actually set the friction to a non-zero value (like 4.0) you would have seen the circle actually rotate and roll across the screen instead of gliding across the screen. Actually, you need to set the friction to a non-zero value for both the platforms and the player object.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> makeBox2dObjAt<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CGPoint<span style="color: #002200;">&#41;</span>p 
			   withSize<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CGPoint<span style="color: #002200;">&#41;</span>size 
				dynamic<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">BOOL</span><span style="color: #002200;">&#41;</span>d 
			   rotation<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">long</span><span style="color: #002200;">&#41;</span>r 
			   friction<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">long</span><span style="color: #002200;">&#41;</span>f 
				density<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">long</span><span style="color: #002200;">&#41;</span>dens 
			restitution<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">long</span><span style="color: #002200;">&#41;</span>rest 
				  boxId<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">int</span><span style="color: #002200;">&#41;</span>boxId <span style="color: #002200;">&#123;</span>
&nbsp;
	<span style="color: #11740a; font-style: italic;">// Define the dynamic body.</span>
	<span style="color: #11740a; font-style: italic;">//Set up a 1m squared box in the physics world</span>
	b2BodyDef bodyDef;
<span style="color: #11740a; font-style: italic;">//	bodyDef.angle = r;</span>
&nbsp;
	bodyDef.position.Set<span style="color: #002200;">&#40;</span>p.x<span style="color: #002200;">/</span>PTM_RATIO, p.y<span style="color: #002200;">/</span>PTM_RATIO<span style="color: #002200;">&#41;</span>;
	bodyDef.userData <span style="color: #002200;">=</span> <span style="color: #a61390;">NULL</span>;
	<span style="color: #11740a; font-style: italic;">//bodyDef.userData = sprite;</span>
&nbsp;
	b2Body <span style="color: #002200;">*</span>body <span style="color: #002200;">=</span> world<span style="color: #002200;">-</span>&gt;CreateBody<span style="color: #002200;">&#40;</span><span style="color: #002200;">&amp;</span>bodyDef<span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// Define another box shape for our dynamic body.</span>
	b2PolygonShape dynamicBox;
	dynamicBox.SetAsBox<span style="color: #002200;">&#40;</span>size.x<span style="color: #002200;">/</span><span style="color: #2400d9;">2</span><span style="color: #002200;">/</span>PTM_RATIO, size.y<span style="color: #002200;">/</span><span style="color: #2400d9;">2</span><span style="color: #002200;">/</span>PTM_RATIO<span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// Define the dynamic body fixture.</span>
	b2FixtureDef fixtureDef;
	fixtureDef.shape <span style="color: #002200;">=</span> <span style="color: #002200;">&amp;</span>dynamicBox;	
	fixtureDef.density <span style="color: #002200;">=</span> dens;
	fixtureDef.friction <span style="color: #002200;">=</span> f;
	fixtureDef.restitution <span style="color: #002200;">=</span> rest;
	body<span style="color: #002200;">-</span>&gt;CreateFixture<span style="color: #002200;">&#40;</span><span style="color: #002200;">&amp;</span>fixtureDef<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre></div></div>

<p>The method above handles the Box2D object creation. It is standard code for creating a Box2D object. Please refer to <a href="http://www.uchidacoonga.com/2011/01/lesson-1-beginning-box2d-physics-engine/">Beginning Box2D Physics Engine</a> if you do not understand the code above.</p>
<h4><span style="color: #ff6600;"><strong>Let&#8217;s Continue&#8230;</strong></span></h4>
<p>Now, let&#8217;s put everything together.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span> init <span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">if</span><span style="color: #002200;">&#40;</span> <span style="color: #002200;">&#40;</span>self<span style="color: #002200;">=</span><span style="color: #002200;">&#91;</span>super init<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
		b2Vec2 gravity <span style="color: #002200;">=</span> b2Vec2<span style="color: #002200;">&#40;</span>0.0f, <span style="color: #002200;">-</span>9.8f<span style="color: #002200;">&#41;</span>;
		bool doSleep <span style="color: #002200;">=</span> <span style="color: #a61390;">true</span>;
		world <span style="color: #002200;">=</span> new b2World<span style="color: #002200;">&#40;</span>gravity, doSleep<span style="color: #002200;">&#41;</span>;
&nbsp;
		m_debugDraw <span style="color: #002200;">=</span> new GLESDebugDraw<span style="color: #002200;">&#40;</span>PTM_RATIO<span style="color: #002200;">&#41;</span>;
		world<span style="color: #002200;">-</span>&gt;SetDebugDraw<span style="color: #002200;">&#40;</span>m_debugDraw<span style="color: #002200;">&#41;</span>;
		uint32 flags <span style="color: #002200;">=</span> <span style="color: #2400d9;">0</span>;
		flags <span style="color: #002200;">+=</span> b2DebugDraw<span style="color: #002200;">::</span>e_shapeBit;
		m_debugDraw<span style="color: #002200;">-</span>&gt;SetFlags<span style="color: #002200;">&#40;</span>flags<span style="color: #002200;">&#41;</span>;
&nbsp;
&nbsp;
		<span style="color: #002200;">&#91;</span>self addScrollingBackgroundWithTileMap<span style="color: #002200;">&#93;</span>;
		<span style="color: #002200;">&#91;</span>self drawCollisionTiles<span style="color: #002200;">&#93;</span>;
&nbsp;
		CCSprite <span style="color: #002200;">*</span>sprite <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>CCSprite spriteWithFile<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Icon-Small.png&quot;</span><span style="color: #002200;">&#93;</span>;
		sprite.position <span style="color: #002200;">=</span> ccp<span style="color: #002200;">&#40;</span>100.0f, 180.0f<span style="color: #002200;">&#41;</span>;
&nbsp;
		<span style="color: #002200;">&#91;</span>self addChild<span style="color: #002200;">:</span>sprite<span style="color: #002200;">&#93;</span>;
&nbsp;
		b2BodyDef playerBodyDef;
		playerBodyDef.type <span style="color: #002200;">=</span> b2_dynamicBody;
		playerBodyDef.position.Set<span style="color: #002200;">&#40;</span>sprite.position.x<span style="color: #002200;">/</span>PTM_RATIO, sprite.position.y<span style="color: #002200;">/</span>PTM_RATIO<span style="color: #002200;">&#41;</span>;
		playerBodyDef.userData <span style="color: #002200;">=</span> sprite;
&nbsp;
		playerBody <span style="color: #002200;">=</span> world<span style="color: #002200;">-</span>&gt;CreateBody<span style="color: #002200;">&#40;</span><span style="color: #002200;">&amp;</span>playerBodyDef<span style="color: #002200;">&#41;</span>;
&nbsp;
		b2CircleShape circleShape;
		circleShape.m_radius <span style="color: #002200;">=</span> 1.0f;
&nbsp;
		b2FixtureDef fixtureDef;
		fixtureDef.shape <span style="color: #002200;">=</span> <span style="color: #002200;">&amp;</span>circleShape;
		fixtureDef.density <span style="color: #002200;">=</span> 1.0f;
		fixtureDef.friction <span style="color: #002200;">=</span> 0.0f;
		fixtureDef.restitution <span style="color: #002200;">=</span>  0.0f;
		playerBody<span style="color: #002200;">-</span>&gt;CreateFixture<span style="color: #002200;">&#40;</span><span style="color: #002200;">&amp;</span>fixtureDef<span style="color: #002200;">&#41;</span>;
&nbsp;
		b2Vec2 impulse <span style="color: #002200;">=</span> b2Vec2<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">10</span>, <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>;
		playerBody<span style="color: #002200;">-</span>&gt;ApplyLinearImpulse<span style="color: #002200;">&#40;</span>impulse, playerBody<span style="color: #002200;">-</span>&gt;GetWorldCenter<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;		
&nbsp;
		<span style="color: #002200;">&#91;</span>self scheduleUpdate<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#125;</span>
	<span style="color: #a61390;">return</span> self;
<span style="color: #002200;">&#125;</span></pre></div></div>

<p>First, in the code above, it creates the Box2D world and sets up the debug drawing. It then calls addScrollingBackgroundWithTileMap and drawCollisionTiles to load the tile map and then creates the Box2D objects from the Collision layer. I used the small Cocos2D logo as the sprite for the player object. Standard Box2D object creation code follows, and then an impulse force is applied to the circle to make it move to the right of the screen. Set the impulse force to a bigger value to speed up the scroll speed.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> update<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>ccTime<span style="color: #002200;">&#41;</span>dt <span style="color: #002200;">&#123;</span>
	<span style="color: #11740a; font-style: italic;">//It is recommended that a fixed time step is used with Box2D for stability</span>
	<span style="color: #11740a; font-style: italic;">//of the simulation, however, we are using a variable time step here.</span>
	<span style="color: #11740a; font-style: italic;">//You need to make an informed choice, the following URL is useful</span>
	<span style="color: #11740a; font-style: italic;">//http://gafferongames.com/game-physics/fix-your-timestep/</span>
&nbsp;
	int32 velocityIterations <span style="color: #002200;">=</span> <span style="color: #2400d9;">8</span>;
	int32 positionIterations <span style="color: #002200;">=</span> <span style="color: #2400d9;">1</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// Instruct the world to perform a single step of simulation. It is</span>
	<span style="color: #11740a; font-style: italic;">// generally best to keep the time step and iterations fixed.</span>
	world<span style="color: #002200;">-</span>&gt;Step<span style="color: #002200;">&#40;</span>dt, velocityIterations, positionIterations<span style="color: #002200;">&#41;</span>;
&nbsp;
&nbsp;
	<span style="color: #11740a; font-style: italic;">//Iterate over the bodies in the physics world</span>
	<span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span>b2Body<span style="color: #002200;">*</span> b <span style="color: #002200;">=</span> world<span style="color: #002200;">-</span>&gt;GetBodyList<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>; b; b <span style="color: #002200;">=</span> b<span style="color: #002200;">-</span>&gt;GetNext<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
		<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>b<span style="color: #002200;">-</span>&gt;GetUserData<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">!=</span> <span style="color: #a61390;">NULL</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
			<span style="color: #11740a; font-style: italic;">//Synchronize the AtlasSprites position and rotation with the corresponding body</span>
			CCSprite <span style="color: #002200;">*</span>myActor <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>CCSprite<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>b<span style="color: #002200;">-</span>&gt;GetUserData<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
			myActor.position <span style="color: #002200;">=</span> CGPointMake<span style="color: #002200;">&#40;</span> b<span style="color: #002200;">-</span>&gt;GetPosition<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>.x <span style="color: #002200;">*</span> PTM_RATIO, 
					   b<span style="color: #002200;">-</span>&gt;GetPosition<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>.y <span style="color: #002200;">*</span> PTM_RATIO<span style="color: #002200;">&#41;</span>;
			myActor.rotation <span style="color: #002200;">=</span> <span style="color: #002200;">-</span><span style="color: #2400d9;">1</span> <span style="color: #002200;">*</span> CC_RADIANS_TO_DEGREES<span style="color: #002200;">&#40;</span>b<span style="color: #002200;">-</span>&gt;GetAngle<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;
		<span style="color: #002200;">&#125;</span>	
	<span style="color: #002200;">&#125;</span>	
&nbsp;
	b2Vec2 pos <span style="color: #002200;">=</span> playerBody<span style="color: #002200;">-</span>&gt;GetPosition<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
	CGPoint newPos <span style="color: #002200;">=</span> ccp<span style="color: #002200;">&#40;</span><span style="color: #002200;">-</span><span style="color: #2400d9;">1</span> <span style="color: #002200;">*</span> pos.x <span style="color: #002200;">*</span> PTM_RATIO <span style="color: #002200;">+</span> <span style="color: #2400d9;">50</span>, self.position.y <span style="color: #002200;">*</span> PTM_RATIO<span style="color: #002200;">&#41;</span>;	
	<span style="color: #002200;">&#91;</span>self setPosition<span style="color: #002200;">:</span>newPos<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></div></div>

<p>Again, the block of code above is standard Box2D code to simulate the physics world for a slice of time, updating the sprite position and rotation to the value calculated by the Box2D physics engine. Again, remember to set the friction value to something other than 0.0 to see the circle rotate and roll across the screen instead of gliding. The code to actually scroll the background is the last three lines of the method. First, we get the location of the circle in the Box2D world. Please note that I said <em>Box2D</em> world. The value needs to be converted into pixels because we are setting the new position for a Cocos2D node, so they are multiplied by the constant PTM_RATIO. The &#8220;y&#8221; position is used as is, but the &#8220;x&#8221; position is updated to scroll the screen. The screen is scrolling from right to left, so it is multiplied by negative one. Then a buffer value of 50 is added to move the circle slightly to the right of the screen. If you do not add the buffer value, then the circle will be flushed all the way to the left of the screen with the left half of the circle clipped and only the right half the circle showing.</p>
<h4><span style="color: #ff6600;"><strong>Sample Code</strong></span></h4>
<p>I hope this has been helpful to someone. And here is the <a href="http://www.uchidacoonga.com/SimpleBox2dScroller.zip">sample code</a>.</p>
<p>Happy coding!</p>

<p><a href="http://feedads.g.doubleclick.net/~a/cvwgKiYpMO_pne1iEXGwRIrIq9g/0/da"><img src="http://feedads.g.doubleclick.net/~a/cvwgKiYpMO_pne1iEXGwRIrIq9g/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/cvwgKiYpMO_pne1iEXGwRIrIq9g/1/da"><img src="http://feedads.g.doubleclick.net/~a/cvwgKiYpMO_pne1iEXGwRIrIq9g/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.uchidacoonga.com/2011/01/side-scrolling-the-background-in-box2d/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Beginning Box2D Physics Engine</title>
		<link>http://www.uchidacoonga.com/2011/01/lesson-1-beginning-box2d-physics-engine/</link>
		<comments>http://www.uchidacoonga.com/2011/01/lesson-1-beginning-box2d-physics-engine/#comments</comments>
		<pubDate>Sat, 08 Jan 2011 05:55:15 +0000</pubDate>
		<dc:creator>Min</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[iPhone Development]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Box2D]]></category>
		<category><![CDATA[Cocos2D]]></category>

		<guid isPermaLink="false">http://www.uchidacoonga.com/?p=769</guid>
		<description><![CDATA[What Is It? Cocos2d comes with two physics engines. One is called Chipmunk and the other is called Box2d. Chipmunk sounds cuter and is written in C, whereas Box2D is written in C++. I chose to learn Box2d because it seems to be the more popular and mature of the two. Instead of trying to <a href='http://www.uchidacoonga.com/2011/01/lesson-1-beginning-box2d-physics-engine/'>... [READ THE FULL ARTICLE]</a>]]></description>
			<content:encoded><![CDATA[<h4><span style="color: #ff6600;"><strong>What Is It?</strong></span></h4>
<p>Cocos2d comes with two physics engines. One is called Chipmunk and the other is called Box2d. Chipmunk sounds cuter and is written in C, whereas Box2D is written in C++. I chose to learn Box2d because it seems to be the more popular and mature of the two. Instead of trying to explain what a physics engine is, it is probably better for you to read the full definition on <a href="http://en.wikipedia.org/wiki/Physics_engine">Wikipedia</a>. Pretty cool! So how does Box2d physics engine work with Cocos2D? It is fairly simple. The way Box2d interacts with Cocos2d is that you update the positions of your Cocos2d objects with the positions calculated by Box2d. </p>
<h4><span style="color: #ff6600;"><strong>Getting Started</strong></span></h4>
<p><a href="http://www.uchidacoonga.com/2011/01/lesson-1-beginning-box2d-physics-engine/screen-shot-2011-01-06-at-10-33-00-pm-2/" rel="attachment wp-att-777"><img src="http://www.uchidacoonga.com/wp-content/uploads/2011/01/Screen-shot-2011-01-06-at-10.33.00-PM-2-300x206.png" alt="" title="Screen shot 2011-01-06 at 10.33.00 PM (2)" width="300" height="206" class="alignleft size-medium wp-image-777" /></a>When you create a new Cocos2d project, there is an application template called &#8220;cocos2d box2d Application&#8221;. If you select that, you will have a sample Box2D Cocos2d application that you can compile and test right away. I am going to try to deconstruct the sample Box2d application, attempting to explain the individual pieces of the code. In the sample application, you touch the screen and a box is created at the location that you touch the screen. The box falls to the ground following the law of gravity and also interacts with the ground and other boxes. Take a look at the image to your left or the video of the application in action below.</p>
<p><iframe src="http://player.vimeo.com/video/18556063" width="400" height="300" frameborder="0"></iframe>
<p><a href="http://vimeo.com/18556063">Cocos2D Box2D Sample App</a> from <a href="http://vimeo.com/user2125614">Min K</a> on <a href="http://vimeo.com">Vimeo</a>.</p>
<h4><span style="color: #ff6600;"><strong>Definitions and Idiosyncrasies </strong></span></h4>
<p>Here are some terms that you will see being used when people talk about Box2D and physics engines. Along with the definitions are a few things you should know about Box2d before you get started. It is probably a good idea to at least skim over them. You can find most of the definitions on the Box2d web site, but I will include it here for convenience.</p>
<p><strong>Shape</strong> is a 2 dimensional geometrical object, such as a circle, square or a polygon.</p>
<p><strong>Rigid bodies</strong> are physics objects that are, well, rigid or stiff. They do not change shape (like being squish-able). </p>
<p><strong>Dynamic bodies</strong> are objects that interact with objects in the world. They have attributes such as density, friction and restitution. </p>
<p><strong>Static bodies</strong> are objects that are the opposite of dynamic bodies. Objects that are static bodies do not move. Static bodies only collide with dynamic bodies and do not collide with other static bodies.</p>
<p><strong>Constraint</strong> is a physical connection that removes degrees of freedom from bodies. In 2 dimensions, a body has 3 degrees of freedom (two translation coordinates and one rotating coordinate). If we take a body and pin it to the wall (like a pendulum) we have constrained the body to the wall. At this point the body can only rotate about the pin, so the constraint has removed 2 degrees of freedom.</p>
<p><strong>Fixture</strong> binds a shape to a body and adds material properties such as density, friction, and restitution (body is a parent of a fixture).</p>
<p><strong>Friction</strong> determines how slippery the object is when moving over a surface. </p>
<p><strong>Density or mass</strong> determines the weight of the object. The heavier it is, the harder it is to move, for example.</p>
<p><strong>Restitution</strong> determines the bounciness of the object. </p>
<p><strong>Joints</strong> can be used to connect together bodies.</p>
<p><strong>Joint limit</strong> restricts the range of motion of a joint. For example, the human elbow allows a certain range of angles.</p>
<p><strong>Joint motor</strong> drives the motion of the connected bodies according to the joint&#8217;s degrees of freedom. For example, you can use a motor to drive the rotation of an elbow.</p>
<p><strong>Sleeping bodies</strong> are bodies that have come to rest and do not need to be processed by the physics engine. </p>
<p><strong>World</strong> means a physics world with a collection of bodies, fixtures and constraints that interact together. Box2D supports the creation of multiple worlds, but this is usually not necessary or desirable.</p>
<p>Here are some things to keep in mind about Box2D.</p>
<ol>
<li>Box2d does all its maths using the metric system (meters, kilograms, seconds aka MKS units).</li>
<li>Box2d uses radians for angles.</li>
<li>Box2d works best with objects that are between 0.1 and 10 meters. But it is the most optical if you keep your game objects close to 1 meter as possible.</li>
<li>You&#8217;ll notice a constant called PTM_RATIO (value is 32) in the sample. You can use it to convert pixels to meters (divide by PTM_RATIO) and meters to pixels (multiply by PTM_RATIO). You can set PTM_RATIO to any value you want, but you should pick a good value so that when divided by it, the resulting value will be no less than 0.1 meters and no more than 10 meters (and optimally close to 1 meter as possible).</li>
<li>Box2d is C++, so make sure to use C++ memory allocation and deallocations. If you are mixing Objective-C with C++ code, the file extension must be .mm (not .m).</li>
</ol>
<h4><span style="color: #ff6600;"><strong>Breakdown of the Code</strong></span></h4>
<p>You can find the complete code further down the screen. Here, I&#8217;m going to explain the code in pieces so that it is more readable and manageable.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">@interface</span> HelloWorld <span style="color: #002200;">:</span> CCLayer <span style="color: #002200;">&#123;</span>
	b2World<span style="color: #002200;">*</span> world;
	GLESDebugDraw <span style="color: #002200;">*</span>m_debugDraw;
<span style="color: #002200;">&#125;</span></pre></div></div>

<p>The block of code above should be in the header. We declare a b2World pointer and a GLESDebugDraw pointer. The b2World pointer is the physics world that will hold all the physics objects. GLESDebugDraw allows any Box2D bodies to be shown (i.e. outlined), instead of using a sprite. It is a useful verification and debugging tool. When you are ready for production, you want to get rid of DebugDraw and use your real art work.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// Define the gravity vector.</span>
b2Vec2 gravity;
gravity.Set<span style="color: #002200;">&#40;</span>0.0f, <span style="color: #002200;">-</span>10.0f<span style="color: #002200;">&#41;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// Do we want to let bodies sleep?</span>
<span style="color: #11740a; font-style: italic;">// This will speed up the physics simulation</span>
bool doSleep <span style="color: #002200;">=</span> <span style="color: #a61390;">true</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// Construct a world object, which will hold and simulate the rigid bodies.</span>
world <span style="color: #002200;">=</span> new b2World<span style="color: #002200;">&#40;</span>gravity, doSleep<span style="color: #002200;">&#41;</span>;
&nbsp;
world<span style="color: #002200;">-</span>&gt;SetContinuousPhysics<span style="color: #002200;">&#40;</span><span style="color: #a61390;">true</span><span style="color: #002200;">&#41;</span>;</pre></div></div>

<p>You will see the block of code above inside the init method. First, you define the gravity vector to point downward at -10.0. Recall that gravity is 9.8 meters per second squared, so we just use -10.0 to approximate gravity (negative because it is going down in the Y direction). Then, the Box2d world is created with the doSleep boolean variable is set to true, which means that bodies in the world are allowed to sleep when they come to rest. A sleeping body does not require simulation and thus does not require processing. This translates into better performance.</p>
<p>The Box2D manual states that SetContinuousPhysics(true) is more for testing purposes and is used for fast moving objects and continuous collision detection (CCD). The Box2D&#8217;s manual states the following regarding CCD.</p>
<blockquote><p>By default, Box2D uses continuous collision detection (CCD) to prevent dynamic bodies from tunneling through static bodies. This is done by sweeping shapes from their old position to their new positions. The engine looks for new collisions during the sweep and computes the time of impact (TOI) for these collisions. Bodies are moved to their first TOI and then halted for the remainder of the time step.</p>
<p>Normally CCD is not used between dynamic bodies. This is done to keep performance reasonable. In some game scenarios you need dynamic bodies to use CCD. For example, you may want to shoot a high speed bullet at a stack of dynamic bricks. Without CCD, the bullet might tunnel through the bricks.</p></blockquote>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;">uint32 flags <span style="color: #002200;">=</span> <span style="color: #2400d9;">0</span>;
flags <span style="color: #002200;">+=</span> b2DebugDraw<span style="color: #002200;">::</span>e_shapeBit;
m_debugDraw<span style="color: #002200;">-</span>&gt;SetFlags<span style="color: #002200;">&#40;</span>flags<span style="color: #002200;">&#41;</span>;				
&nbsp;
<span style="color: #11740a; font-style: italic;">// Define the ground body.</span>
b2BodyDef groundBodyDef;
<span style="color: #11740a; font-style: italic;">// Explicitly added here for clarity by me.</span>
groundBodyDef.type <span style="color: #002200;">=</span> b2_staticBody;
groundBodyDef.position.Set<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">0</span>, <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>; <span style="color: #11740a; font-style: italic;">// bottom-left corner</span>
&nbsp;
<span style="color: #11740a; font-style: italic;">// Call the body factory which allocates memory for the ground body</span>
<span style="color: #11740a; font-style: italic;">// from a pool and creates the ground box shape (also from a pool).</span>
<span style="color: #11740a; font-style: italic;">// The body is also added to the world.</span>
b2Body<span style="color: #002200;">*</span> groundBody <span style="color: #002200;">=</span> world<span style="color: #002200;">-</span>&gt;CreateBody<span style="color: #002200;">&#40;</span><span style="color: #002200;">&amp;</span>groundBodyDef<span style="color: #002200;">&#41;</span>;</pre></div></div>

<p>Next, you set up the the GLESDebugDraw. You are interested in drawing shapes, so you set the bit to the e_shapeBit (some of the other available bits are e_jointBit, e_aabbBit, e_pairBit and e_centerOfMassBit  &#8212; please check the reference for detailed information on them). You then define the body object for the ground and set the position. Remember that (0, 0) is the lower-left corner in Cocos2d and Box2D. You then call the factory method to create the body by calling the CreateBody function, passing in the reference to the b2BodyDef so that it can fill in the values. The ground is a static body (as opposed to a dynamic body). Remember, a static body do not collide with each other and are immovable. A body is static when it has zero mass. Bodies have zero mass by default, so it is static by default. The line &#8220;groundBodyDef.type = b2_staticBody;&#8221; is not in the code when you create the sample Box2D application from the template, but I explicitly added it here for clarity. After creating the body, you must create the fixture, which is done with the code below.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// Define the ground box shape.</span>
b2PolygonShape groundBox;		
&nbsp;
<span style="color: #11740a; font-style: italic;">// bottom</span>
groundBox.SetAsEdge<span style="color: #002200;">&#40;</span>b2Vec2<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">0</span>,<span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>, b2Vec2<span style="color: #002200;">&#40;</span>screenSize.width<span style="color: #002200;">/</span>PTM_RATIO,<span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;
groundBody<span style="color: #002200;">-</span>&gt;CreateFixture<span style="color: #002200;">&#40;</span><span style="color: #002200;">&amp;</span>groundBox,<span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// top</span>
groundBox.SetAsEdge<span style="color: #002200;">&#40;</span>b2Vec2<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">0</span>,screenSize.height<span style="color: #002200;">/</span>PTM_RATIO<span style="color: #002200;">&#41;</span>, 
                 b2Vec2<span style="color: #002200;">&#40;</span>screenSize.width<span style="color: #002200;">/</span>PTM_RATIO,screenSize.height<span style="color: #002200;">/</span>PTM_RATIO<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;
groundBody<span style="color: #002200;">-</span>&gt;CreateFixture<span style="color: #002200;">&#40;</span><span style="color: #002200;">&amp;</span>groundBox,<span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// left</span>
groundBox.SetAsEdge<span style="color: #002200;">&#40;</span>b2Vec2<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">0</span>,screenSize.height<span style="color: #002200;">/</span>PTM_RATIO<span style="color: #002200;">&#41;</span>, b2Vec2<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">0</span>,<span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;
groundBody<span style="color: #002200;">-</span>&gt;CreateFixture<span style="color: #002200;">&#40;</span><span style="color: #002200;">&amp;</span>groundBox,<span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// right</span>
groundBox.SetAsEdge<span style="color: #002200;">&#40;</span>b2Vec2<span style="color: #002200;">&#40;</span>screenSize.width<span style="color: #002200;">/</span>PTM_RATIO,screenSize.height<span style="color: #002200;">/</span>PTM_RATIO<span style="color: #002200;">&#41;</span>, 
                   b2Vec2<span style="color: #002200;">&#40;</span>screenSize.width<span style="color: #002200;">/</span>PTM_RATIO,<span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;
groundBody<span style="color: #002200;">-</span>&gt;CreateFixture<span style="color: #002200;">&#40;</span><span style="color: #002200;">&amp;</span>groundBox,<span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>;</pre></div></div>

<p>The code above creates the fixtures to attach to the body. Recall that a fixture must be a child to a body and that the width and height are divided by PTM_RATIO to convert pixels to meters. We create a fixture for each side of the box (top, bottom, left and right) and attach it to the body. The second parameter to CreateFixture denotes the density (which is 0). Here, you passed the shape to the CreateFixture function, but there is another way to create a fixture. There is an overloaded CreateFixture function that takes a b2FixtureDef instead.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// Note: Not part of the sample code -- just here for illustration</span>
b2FixtureDef groundFixtureDef;
groundFixtureDef.type <span style="color: #002200;">=</span> b2_staticBody;
groundFixtureDef.position.Set<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">0</span>, <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// Then you pass the reference to groundFixtureDef to CreateFixture instead.</span>
<span style="color: #11740a; font-style: italic;">// bottom</span>
groundBox.SetAsEdge<span style="color: #002200;">&#40;</span>b2Vec2<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">0</span>,<span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>, b2Vec2<span style="color: #002200;">&#40;</span>screenSize.width<span style="color: #002200;">/</span>PTM_RATIO,<span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;
groundBox.CreateFixture<span style="color: #002200;">&#40;</span><span style="color: #002200;">&amp;</span>groundFixtureDef<span style="color: #002200;">&#41;</span>;
...
<span style="color: #11740a; font-style: italic;">// do similar for top, left and right</span></pre></div></div>

<p>The rest of the code in init is normal Cocos2D code &#8212; it adds a sprite image, adds a label and then schedules a timer to call the method called tick. Now, for the rest of the code.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> draw <span style="color: #002200;">&#123;</span>
   glDisable<span style="color: #002200;">&#40;</span>GL_TEXTURE_2D<span style="color: #002200;">&#41;</span>;
   glDisableClientState<span style="color: #002200;">&#40;</span>GL_COLOR_ARRAY<span style="color: #002200;">&#41;</span>;
   glDisableClientState<span style="color: #002200;">&#40;</span>GL_TEXTURE_COORD_ARRAY<span style="color: #002200;">&#41;</span>;
&nbsp;
   world<span style="color: #002200;">-</span>&gt;DrawDebugData<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
   <span style="color: #11740a; font-style: italic;">// restore default GL states</span>
   glEnable<span style="color: #002200;">&#40;</span>GL_TEXTURE_2D<span style="color: #002200;">&#41;</span>;
   glEnableClientState<span style="color: #002200;">&#40;</span>GL_COLOR_ARRAY<span style="color: #002200;">&#41;</span>;
   glEnableClientState<span style="color: #002200;">&#40;</span>GL_TEXTURE_COORD_ARRAY<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre></div></div>

<p>The draw method is where OpenGL calls take place. This is where you call the DrawDebugData() function (for GLESDebugDraw). OpenGL is a state based, so you need to disable certain states before DrawDebugData() is called and re-enable them after. You don&#8217;t have to know the details. This is the code provided by the template, so it is enough to copy/paste the code above and simply remember to disable and enable them as done above.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>ccTouchesEnded<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSSet</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>touches withEvent<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIEvent <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>event <span style="color: #002200;">&#123;</span>
   <span style="color: #11740a; font-style: italic;">//Add a new body/atlas sprite at the touched location</span>
   <span style="color: #a61390;">for</span><span style="color: #002200;">&#40;</span> UITouch <span style="color: #002200;">*</span>touch <span style="color: #a61390;">in</span> touches <span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
      CGPoint location <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>touch locationInView<span style="color: #002200;">:</span> <span style="color: #002200;">&#91;</span>touch view<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
      location <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>CCDirector sharedDirector<span style="color: #002200;">&#93;</span> convertToGL<span style="color: #002200;">:</span> location<span style="color: #002200;">&#93;</span>;
      <span style="color: #002200;">&#91;</span>self addNewSpriteWithCoords<span style="color: #002200;">:</span> location<span style="color: #002200;">&#93;</span>;
   <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span></pre></div></div>

<p>The method above is triggered when the screen is touched. When the screen is touched, it calls the addNewSpriteWithCoords method, passing in the location of the screen that was touched. The addNewSpriteWithCoords method creates a box at that location. The box that is created with be simulated by the Box2D physics engine (meaning, it will fall at 10.0 (or 9.8) meters or second squared.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> addNewSpriteWithCoords<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CGPoint<span style="color: #002200;">&#41;</span>p <span style="color: #002200;">&#123;</span>
   CCLOG<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Add sprite %0.2f x %02.f&quot;</span>,p.x,p.y<span style="color: #002200;">&#41;</span>;
   CCSpriteBatchNode <span style="color: #002200;">*</span>batch <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>CCSpriteBatchNode<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#91;</span>self getChildByTag<span style="color: #002200;">:</span>kTagBatchNode<span style="color: #002200;">&#93;</span>;
&nbsp;
   <span style="color: #11740a; font-style: italic;">//We have a 64x64 sprite sheet with 4 different 32x32 images.  The following code is</span>
   <span style="color: #11740a; font-style: italic;">//just randomly picking one of the images</span>
   <span style="color: #a61390;">int</span> idx <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>CCRANDOM_0_1<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span> &gt; .5 ? <span style="color: #2400d9;">0</span><span style="color: #002200;">:</span><span style="color: #2400d9;">1</span><span style="color: #002200;">&#41;</span>;
   <span style="color: #a61390;">int</span> idy <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>CCRANDOM_0_1<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span> &gt; .5 ? <span style="color: #2400d9;">0</span><span style="color: #002200;">:</span><span style="color: #2400d9;">1</span><span style="color: #002200;">&#41;</span>;
   CCSprite <span style="color: #002200;">*</span>sprite <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>CCSprite spriteWithBatchNode<span style="color: #002200;">:</span>batch 
                                rect<span style="color: #002200;">:</span>CGRectMake<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">32</span> <span style="color: #002200;">*</span> idx,<span style="color: #2400d9;">32</span> <span style="color: #002200;">*</span> idy,<span style="color: #2400d9;">32</span>,<span style="color: #2400d9;">32</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
   <span style="color: #002200;">&#91;</span>batch addChild<span style="color: #002200;">:</span>sprite<span style="color: #002200;">&#93;</span>;
&nbsp;
   sprite.position <span style="color: #002200;">=</span> ccp<span style="color: #002200;">&#40;</span> p.x, p.y<span style="color: #002200;">&#41;</span>;
&nbsp;
   <span style="color: #11740a; font-style: italic;">// Define the dynamic body.</span>
   <span style="color: #11740a; font-style: italic;">//Set up a 1m squared box in the physics world</span>
   b2BodyDef bodyDef;
   bodyDef.type <span style="color: #002200;">=</span> b2_dynamicBody;
&nbsp;
   bodyDef.position.Set<span style="color: #002200;">&#40;</span>p.x<span style="color: #002200;">/</span>PTM_RATIO, p.y<span style="color: #002200;">/</span>PTM_RATIO<span style="color: #002200;">&#41;</span>;
   bodyDef.userData <span style="color: #002200;">=</span> sprite;
   b2Body <span style="color: #002200;">*</span>body <span style="color: #002200;">=</span> world<span style="color: #002200;">-</span>&gt;CreateBody<span style="color: #002200;">&#40;</span><span style="color: #002200;">&amp;</span>bodyDef<span style="color: #002200;">&#41;</span>;
&nbsp;
   <span style="color: #11740a; font-style: italic;">// Define another box shape for our dynamic body.</span>
   b2PolygonShape dynamicBox;
   dynamicBox.SetAsBox<span style="color: #002200;">&#40;</span>.5f, .5f<span style="color: #002200;">&#41;</span>;<span style="color: #11740a; font-style: italic;">//These are mid points for our 1m box</span>
&nbsp;
   <span style="color: #11740a; font-style: italic;">// Define the dynamic body fixture.</span>
   b2FixtureDef fixtureDef;
   fixtureDef.shape <span style="color: #002200;">=</span> <span style="color: #002200;">&amp;</span>dynamicBox;	
   fixtureDef.density <span style="color: #002200;">=</span> 1.0f;
   fixtureDef.friction <span style="color: #002200;">=</span> 0.3f;
   body<span style="color: #002200;">-</span>&gt;CreateFixture<span style="color: #002200;">&#40;</span><span style="color: #002200;">&amp;</span>fixtureDef<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre></div></div>

<p>As mentioned, the method above is called when the screen is touched. First, the Cocos2D sprite is created at the location of the touch. Then, a Box2D body is created in order to simulate the physics for that object. It is defined as a dynamic body (b2_dynamicBody). We let Box2D know the position (in meters) and then create the body. A fixture is created with a shape, density and friction and attached to the body. The userData object is a void pointer that can point to any user defined object. Here we set it to the Cocos2d Sprite object for use later. Note that, here, we use the alternative way to create the fixture from b2FixtureDef as explained earlier.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> tick<span style="color: #002200;">:</span> <span style="color: #002200;">&#40;</span>ccTime<span style="color: #002200;">&#41;</span> dt <span style="color: #002200;">&#123;</span>
   <span style="color: #11740a; font-style: italic;">//It is recommended that a fixed time step is used with Box2D for stability</span>
   <span style="color: #11740a; font-style: italic;">//of the simulation, however, we are using a variable time step here.</span>
   <span style="color: #11740a; font-style: italic;">//You need to make an informed choice, the following URL is useful</span>
   <span style="color: #11740a; font-style: italic;">//http://gafferongames.com/game-physics/fix-your-timestep/</span>
&nbsp;
   int32 velocityIterations <span style="color: #002200;">=</span> <span style="color: #2400d9;">8</span>;
   int32 positionIterations <span style="color: #002200;">=</span> <span style="color: #2400d9;">1</span>;
&nbsp;
   <span style="color: #11740a; font-style: italic;">// Instruct the world to perform a single step of simulation. It is</span>
   <span style="color: #11740a; font-style: italic;">// generally best to keep the time step and iterations fixed.</span>
   world<span style="color: #002200;">-</span>&gt;Step<span style="color: #002200;">&#40;</span>dt, velocityIterations, positionIterations<span style="color: #002200;">&#41;</span>;
&nbsp;
&nbsp;
   <span style="color: #11740a; font-style: italic;">//Iterate over the bodies in the physics world</span>
   <span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span>b2Body<span style="color: #002200;">*</span> b <span style="color: #002200;">=</span> world<span style="color: #002200;">-</span>&gt;GetBodyList<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>; b; b <span style="color: #002200;">=</span> b<span style="color: #002200;">-</span>&gt;GetNext<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
      <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>b<span style="color: #002200;">-</span>&gt;GetUserData<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">!=</span> <span style="color: #a61390;">NULL</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
         <span style="color: #11740a; font-style: italic;">//Synchronize the AtlasSprites position and rotation with the corresponding body</span>
	 CCSprite <span style="color: #002200;">*</span>myActor <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>CCSprite<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>b<span style="color: #002200;">-</span>&gt;GetUserData<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
	 myActor.position <span style="color: #002200;">=</span> CGPointMake<span style="color: #002200;">&#40;</span> b<span style="color: #002200;">-</span>&gt;GetPosition<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>.x <span style="color: #002200;">*</span> PTM_RATIO, 
                                    b<span style="color: #002200;">-</span>&gt;GetPosition<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>.y <span style="color: #002200;">*</span> PTM_RATIO<span style="color: #002200;">&#41;</span>;
	 myActor.rotation <span style="color: #002200;">=</span> <span style="color: #002200;">-</span><span style="color: #2400d9;">1</span> <span style="color: #002200;">*</span> CC_RADIANS_TO_DEGREES<span style="color: #002200;">&#40;</span>b<span style="color: #002200;">-</span>&gt;GetAngle<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;
      <span style="color: #002200;">&#125;</span>	
   <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span></pre></div></div>

<p>The tick method above is the method that was scheduled in the init method. You will notice the world->Step() call. As noted in the comment, the Step() function is used to perform a single step of the simulation. You pass in the values for velocity iterations and position iterations as the parameters. These values are used by the physics engine to simulate the physics equations. The higher these numbers are, the better (more accurate) the simulations are, but the tradeoff is performance. So play around with these values to find the right value for your needs. We loop through the list of bodies in the physics world and then update the position and rotation of the sprites (which was stored in userData pointer) with the value that is calculated by Box2D.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>accelerometer<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIAccelerometer<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>accelerometer 
         didAccelerate<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIAcceleration<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>acceleration <span style="color: #002200;">&#123;</span>	
&nbsp;
   <span style="color: #a61390;">static</span> <span style="color: #a61390;">float</span> prevX<span style="color: #002200;">=</span><span style="color: #2400d9;">0</span>, prevY<span style="color: #002200;">=</span><span style="color: #2400d9;">0</span>;
&nbsp;
   <span style="color: #11740a; font-style: italic;">//#define kFilterFactor 0.05f</span>
   <span style="color: #6e371a;">#define kFilterFactor 1.0f	// don't use filter. the code is here just as an example</span>
&nbsp;
   <span style="color: #a61390;">float</span> accelX <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">float</span><span style="color: #002200;">&#41;</span> acceleration.x <span style="color: #002200;">*</span> kFilterFactor <span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span><span style="color: #2400d9;">1</span><span style="color: #002200;">-</span> kFilterFactor<span style="color: #002200;">&#41;</span><span style="color: #002200;">*</span>prevX;
   <span style="color: #a61390;">float</span> accelY <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">float</span><span style="color: #002200;">&#41;</span> acceleration.y <span style="color: #002200;">*</span> kFilterFactor <span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span><span style="color: #2400d9;">1</span><span style="color: #002200;">-</span> kFilterFactor<span style="color: #002200;">&#41;</span><span style="color: #002200;">*</span>prevY;
&nbsp;
   prevX <span style="color: #002200;">=</span> accelX;
   prevY <span style="color: #002200;">=</span> accelY;
&nbsp;
   <span style="color: #11740a; font-style: italic;">// accelerometer values are in &quot;Portrait&quot; mode. Change them to Landscape left</span>
   <span style="color: #11740a; font-style: italic;">// multiply the gravity by 10</span>
   b2Vec2 gravity<span style="color: #002200;">&#40;</span> <span style="color: #002200;">-</span>accelY <span style="color: #002200;">*</span> <span style="color: #2400d9;">10</span>, accelX <span style="color: #002200;">*</span> <span style="color: #2400d9;">10</span><span style="color: #002200;">&#41;</span>;
&nbsp;
   world<span style="color: #002200;">-</span>&gt;SetGravity<span style="color: #002200;">&#40;</span> gravity <span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre></div></div>

<p>Finally, the last block of code merely transforms the accelerometer readings into a Box2D gravity vector. Notice that X and Y values are switched due to the device being in landscape mode. As you tilt your phone, you will see the boxes shifting in the tilt direction. </p>
<h4><span style="color: #ff6600;"><strong>The End</strong></span></h4>
<p>This was a simple exercise, but hopefully it was helpful in getting your head wrapped around the fundamentals. The key ideas to take away from this lesson are that 1. Box2D (physics engine) calculates the positions of the objects and you update the game objects with the values provided by Box2D, 2. physics objects are rigid bodies that can be either static or dynamic and 3. a body can be bound to one or more fixture(s) that define material properties such as the shape, density, friction and restitution. </p>
<p>In a future post, I am going to try doing something a bit more exciting than the sample application. So please stay tuned! </p>
<h4><span style="color: #ff6600;"><strong>The Complete Code</strong></span></h4>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &quot;cocos2d.h&quot;</span>
<span style="color: #6e371a;">#import &quot;Box2D.h&quot;</span>
<span style="color: #6e371a;">#import &quot;GLES-Render.h&quot;</span>
&nbsp;
<span style="color: #11740a; font-style: italic;">// HelloWorld Layer</span>
<span style="color: #a61390;">@interface</span> HelloWorld <span style="color: #002200;">:</span> CCLayer
<span style="color: #002200;">&#123;</span>
	b2World<span style="color: #002200;">*</span> world;
	GLESDebugDraw <span style="color: #002200;">*</span>m_debugDraw;
<span style="color: #002200;">&#125;</span>
<span style="color: #11740a; font-style: italic;">// returns a Scene that contains the HelloWorld as the only child</span>
<span style="color: #002200;">+</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span> scene;
&nbsp;
<span style="color: #11740a; font-style: italic;">// adds a new sprite at a given coordinate</span>
<span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> addNewSpriteWithCoords<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CGPoint<span style="color: #002200;">&#41;</span>p;
<span style="color: #a61390;">@end</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &quot;HelloWorldScene.h&quot;</span>
&nbsp;
<span style="color: #11740a; font-style: italic;">//Pixel to metres ratio. Box2D uses metres as the unit for measurement.</span>
<span style="color: #11740a; font-style: italic;">//This ratio defines how many pixels correspond to 1 Box2D &quot;metre&quot;</span>
<span style="color: #11740a; font-style: italic;">//Box2D is optimized for objects of 1x1 metre therefore it makes sense</span>
<span style="color: #11740a; font-style: italic;">//to define the ratio so that your most common object type is 1x1 metre.</span>
<span style="color: #6e371a;">#define PTM_RATIO 32</span>
&nbsp;
<span style="color: #11740a; font-style: italic;">// enums that will be used as tags</span>
<span style="color: #a61390;">enum</span> <span style="color: #002200;">&#123;</span>
	kTagTileMap <span style="color: #002200;">=</span> <span style="color: #2400d9;">1</span>,
	kTagBatchNode <span style="color: #002200;">=</span> <span style="color: #2400d9;">1</span>,
	kTagAnimation1 <span style="color: #002200;">=</span> <span style="color: #2400d9;">1</span>,
<span style="color: #002200;">&#125;</span>;
&nbsp;
<span style="color: #a61390;">@implementation</span> HelloWorld
&nbsp;
<span style="color: #002200;">+</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span> scene <span style="color: #002200;">&#123;</span>
	<span style="color: #11740a; font-style: italic;">// 'scene' is an autorelease object.</span>
	CCScene <span style="color: #002200;">*</span>scene <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>CCScene node<span style="color: #002200;">&#93;</span>;
	HelloWorld <span style="color: #002200;">*</span>layer <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>HelloWorld node<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>scene addChild<span style="color: #002200;">:</span> layer<span style="color: #002200;">&#93;</span>;
	<span style="color: #a61390;">return</span> scene;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span> init <span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">if</span><span style="color: #002200;">&#40;</span> <span style="color: #002200;">&#40;</span>self<span style="color: #002200;">=</span><span style="color: #002200;">&#91;</span>super init<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        <span style="color: #11740a; font-style: italic;">// enable touches</span>
	self.isTouchEnabled <span style="color: #002200;">=</span> <span style="color: #a61390;">YES</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// enable accelerometer</span>
	self.isAccelerometerEnabled <span style="color: #002200;">=</span> <span style="color: #a61390;">YES</span>;
&nbsp;
	CGSize screenSize <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>CCDirector sharedDirector<span style="color: #002200;">&#93;</span>.winSize;
	CCLOG<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Screen width %0.2f screen height %0.2f&quot;</span>,screenSize.width,screenSize.height<span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// Define the gravity vector.</span>
	b2Vec2 gravity;
	gravity.Set<span style="color: #002200;">&#40;</span>0.0f, <span style="color: #002200;">-</span>10.0f<span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// Do we want to let bodies sleep?</span>
	<span style="color: #11740a; font-style: italic;">// This will speed up the physics simulation</span>
	bool doSleep <span style="color: #002200;">=</span> <span style="color: #a61390;">true</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// Construct a world object, which will hold and simulate the rigid bodies.</span>
	world <span style="color: #002200;">=</span> new b2World<span style="color: #002200;">&#40;</span>gravity, doSleep<span style="color: #002200;">&#41;</span>;
&nbsp;
	world<span style="color: #002200;">-</span>&gt;SetContinuousPhysics<span style="color: #002200;">&#40;</span><span style="color: #a61390;">true</span><span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// Debug Draw functions</span>
	m_debugDraw <span style="color: #002200;">=</span> new GLESDebugDraw<span style="color: #002200;">&#40;</span> PTM_RATIO <span style="color: #002200;">&#41;</span>;
	world<span style="color: #002200;">-</span>&gt;SetDebugDraw<span style="color: #002200;">&#40;</span>m_debugDraw<span style="color: #002200;">&#41;</span>;
&nbsp;
	uint32 flags <span style="color: #002200;">=</span> <span style="color: #2400d9;">0</span>;
	flags <span style="color: #002200;">+=</span> b2DebugDraw<span style="color: #002200;">::</span>e_shapeBit;
	m_debugDraw<span style="color: #002200;">-</span>&gt;SetFlags<span style="color: #002200;">&#40;</span>flags<span style="color: #002200;">&#41;</span>;		
&nbsp;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// Define the ground body.</span>
	b2BodyDef groundBodyDef;
	groundBodyDef.position.Set<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">0</span>, <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>; <span style="color: #11740a; font-style: italic;">// bottom-left corner</span>
&nbsp;
	<span style="color: #11740a; font-style: italic;">// Call the body factory which allocates memory for the ground body</span>
	<span style="color: #11740a; font-style: italic;">// from a pool and creates the ground box shape (also from a pool).</span>
	<span style="color: #11740a; font-style: italic;">// The body is also added to the world.</span>
	b2Body<span style="color: #002200;">*</span> groundBody <span style="color: #002200;">=</span> world<span style="color: #002200;">-</span>&gt;CreateBody<span style="color: #002200;">&#40;</span><span style="color: #002200;">&amp;</span>groundBodyDef<span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// Define the ground box shape.</span>
	b2PolygonShape groundBox;		
&nbsp;
	<span style="color: #11740a; font-style: italic;">// bottom</span>
	groundBox.SetAsEdge<span style="color: #002200;">&#40;</span>b2Vec2<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">0</span>,<span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>, b2Vec2<span style="color: #002200;">&#40;</span>screenSize.width<span style="color: #002200;">/</span>PTM_RATIO,<span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;
	groundBody<span style="color: #002200;">-</span>&gt;CreateFixture<span style="color: #002200;">&#40;</span><span style="color: #002200;">&amp;</span>groundBox,<span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// top</span>
	groundBox.SetAsEdge<span style="color: #002200;">&#40;</span>b2Vec2<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">0</span>,screenSize.height<span style="color: #002200;">/</span>PTM_RATIO<span style="color: #002200;">&#41;</span>, 
                       b2Vec2<span style="color: #002200;">&#40;</span>screenSize.width<span style="color: #002200;">/</span>PTM_RATIO,screenSize.height<span style="color: #002200;">/</span>PTM_RATIO<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;
	groundBody<span style="color: #002200;">-</span>&gt;CreateFixture<span style="color: #002200;">&#40;</span><span style="color: #002200;">&amp;</span>groundBox,<span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// left</span>
	groundBox.SetAsEdge<span style="color: #002200;">&#40;</span>b2Vec2<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">0</span>,screenSize.height<span style="color: #002200;">/</span>PTM_RATIO<span style="color: #002200;">&#41;</span>, b2Vec2<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">0</span>,<span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;
	groundBody<span style="color: #002200;">-</span>&gt;CreateFixture<span style="color: #002200;">&#40;</span><span style="color: #002200;">&amp;</span>groundBox,<span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// right</span>
	groundBox.SetAsEdge<span style="color: #002200;">&#40;</span>b2Vec2<span style="color: #002200;">&#40;</span>screenSize.width<span style="color: #002200;">/</span>PTM_RATIO,screenSize.height<span style="color: #002200;">/</span>PTM_RATIO<span style="color: #002200;">&#41;</span>, 
                          b2Vec2<span style="color: #002200;">&#40;</span>screenSize.width<span style="color: #002200;">/</span>PTM_RATIO,<span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;
	groundBody<span style="color: #002200;">-</span>&gt;CreateFixture<span style="color: #002200;">&#40;</span><span style="color: #002200;">&amp;</span>groundBox,<span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>;
&nbsp;
&nbsp;
	<span style="color: #11740a; font-style: italic;">//Set up sprite</span>
	CCSpriteBatchNode <span style="color: #002200;">*</span>batch <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>CCSpriteBatchNode batchNodeWithFile<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;blocks.png&quot;</span> 
                                          capacity<span style="color: #002200;">:</span><span style="color: #2400d9;">150</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>self addChild<span style="color: #002200;">:</span>batch z<span style="color: #002200;">:</span><span style="color: #2400d9;">0</span> tag<span style="color: #002200;">:</span>kTagBatchNode<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #002200;">&#91;</span>self addNewSpriteWithCoords<span style="color: #002200;">:</span>ccp<span style="color: #002200;">&#40;</span>screenSize.width<span style="color: #002200;">/</span><span style="color: #2400d9;">2</span>, screenSize.height<span style="color: #002200;">/</span><span style="color: #2400d9;">2</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
	CCLabelTTF <span style="color: #002200;">*</span>label <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>CCLabelTTF labelWithString<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Tap screen&quot;</span> 
                                          fontName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Marker Felt&quot;</span> fontSize<span style="color: #002200;">:</span><span style="color: #2400d9;">32</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>self addChild<span style="color: #002200;">:</span>label z<span style="color: #002200;">:</span><span style="color: #2400d9;">0</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>label setColor<span style="color: #002200;">:</span>ccc3<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">0</span>,<span style="color: #2400d9;">0</span>,<span style="color: #2400d9;">255</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
	label.position <span style="color: #002200;">=</span> ccp<span style="color: #002200;">&#40;</span> screenSize.width<span style="color: #002200;">/</span><span style="color: #2400d9;">2</span>, screenSize.height<span style="color: #002200;">-</span><span style="color: #2400d9;">50</span><span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #002200;">&#91;</span>self schedule<span style="color: #002200;">:</span> <span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>tick<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>
    <span style="color: #a61390;">return</span> self;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> draw <span style="color: #002200;">&#123;</span>
   glDisable<span style="color: #002200;">&#40;</span>GL_TEXTURE_2D<span style="color: #002200;">&#41;</span>;
   glDisableClientState<span style="color: #002200;">&#40;</span>GL_COLOR_ARRAY<span style="color: #002200;">&#41;</span>;
   glDisableClientState<span style="color: #002200;">&#40;</span>GL_TEXTURE_COORD_ARRAY<span style="color: #002200;">&#41;</span>;
&nbsp;
   world<span style="color: #002200;">-</span>&gt;DrawDebugData<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
   <span style="color: #11740a; font-style: italic;">// restore default GL states</span>
   glEnable<span style="color: #002200;">&#40;</span>GL_TEXTURE_2D<span style="color: #002200;">&#41;</span>;
   glEnableClientState<span style="color: #002200;">&#40;</span>GL_COLOR_ARRAY<span style="color: #002200;">&#41;</span>;
   glEnableClientState<span style="color: #002200;">&#40;</span>GL_TEXTURE_COORD_ARRAY<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> addNewSpriteWithCoords<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CGPoint<span style="color: #002200;">&#41;</span>p <span style="color: #002200;">&#123;</span>
   CCLOG<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Add sprite %0.2f x %02.f&quot;</span>,p.x,p.y<span style="color: #002200;">&#41;</span>;
   CCSpriteBatchNode <span style="color: #002200;">*</span>batch <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>CCSpriteBatchNode<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#91;</span>self getChildByTag<span style="color: #002200;">:</span>kTagBatchNode<span style="color: #002200;">&#93;</span>;
&nbsp;
   <span style="color: #11740a; font-style: italic;">//We have a 64x64 sprite sheet with 4 different 32x32 images.  The following code is</span>
   <span style="color: #11740a; font-style: italic;">//just randomly picking one of the images</span>
   <span style="color: #a61390;">int</span> idx <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>CCRANDOM_0_1<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span> &gt; .5 ? <span style="color: #2400d9;">0</span><span style="color: #002200;">:</span><span style="color: #2400d9;">1</span><span style="color: #002200;">&#41;</span>;
   <span style="color: #a61390;">int</span> idy <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>CCRANDOM_0_1<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span> &gt; .5 ? <span style="color: #2400d9;">0</span><span style="color: #002200;">:</span><span style="color: #2400d9;">1</span><span style="color: #002200;">&#41;</span>;
   CCSprite <span style="color: #002200;">*</span>sprite <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>CCSprite spriteWithBatchNode<span style="color: #002200;">:</span>batch 
                                rect<span style="color: #002200;">:</span>CGRectMake<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">32</span> <span style="color: #002200;">*</span> idx,<span style="color: #2400d9;">32</span> <span style="color: #002200;">*</span> idy,<span style="color: #2400d9;">32</span>,<span style="color: #2400d9;">32</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
   <span style="color: #002200;">&#91;</span>batch addChild<span style="color: #002200;">:</span>sprite<span style="color: #002200;">&#93;</span>;
&nbsp;
   sprite.position <span style="color: #002200;">=</span> ccp<span style="color: #002200;">&#40;</span> p.x, p.y<span style="color: #002200;">&#41;</span>;
&nbsp;
   <span style="color: #11740a; font-style: italic;">// Define the dynamic body.</span>
   <span style="color: #11740a; font-style: italic;">//Set up a 1m squared box in the physics world</span>
   b2BodyDef bodyDef;
   bodyDef.type <span style="color: #002200;">=</span> b2_dynamicBody;
&nbsp;
   bodyDef.position.Set<span style="color: #002200;">&#40;</span>p.x<span style="color: #002200;">/</span>PTM_RATIO, p.y<span style="color: #002200;">/</span>PTM_RATIO<span style="color: #002200;">&#41;</span>;
   bodyDef.userData <span style="color: #002200;">=</span> sprite;
   b2Body <span style="color: #002200;">*</span>body <span style="color: #002200;">=</span> world<span style="color: #002200;">-</span>&gt;CreateBody<span style="color: #002200;">&#40;</span><span style="color: #002200;">&amp;</span>bodyDef<span style="color: #002200;">&#41;</span>;
&nbsp;
   <span style="color: #11740a; font-style: italic;">// Define another box shape for our dynamic body.</span>
   b2PolygonShape dynamicBox;
   dynamicBox.SetAsBox<span style="color: #002200;">&#40;</span>.5f, .5f<span style="color: #002200;">&#41;</span>;<span style="color: #11740a; font-style: italic;">//These are mid points for our 1m box</span>
&nbsp;
   <span style="color: #11740a; font-style: italic;">// Define the dynamic body fixture.</span>
   b2FixtureDef fixtureDef;
   fixtureDef.shape <span style="color: #002200;">=</span> <span style="color: #002200;">&amp;</span>dynamicBox;	
   fixtureDef.density <span style="color: #002200;">=</span> 1.0f;
   fixtureDef.friction <span style="color: #002200;">=</span> 0.3f;
   body<span style="color: #002200;">-</span>&gt;CreateFixture<span style="color: #002200;">&#40;</span><span style="color: #002200;">&amp;</span>fixtureDef<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
&nbsp;
&nbsp;
<span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> tick<span style="color: #002200;">:</span> <span style="color: #002200;">&#40;</span>ccTime<span style="color: #002200;">&#41;</span> dt <span style="color: #002200;">&#123;</span>
   <span style="color: #11740a; font-style: italic;">//It is recommended that a fixed time step is used with Box2D for stability</span>
   <span style="color: #11740a; font-style: italic;">//of the simulation, however, we are using a variable time step here.</span>
   <span style="color: #11740a; font-style: italic;">//You need to make an informed choice, the following URL is useful</span>
   <span style="color: #11740a; font-style: italic;">//http://gafferongames.com/game-physics/fix-your-timestep/</span>
&nbsp;
   int32 velocityIterations <span style="color: #002200;">=</span> <span style="color: #2400d9;">8</span>;
   int32 positionIterations <span style="color: #002200;">=</span> <span style="color: #2400d9;">1</span>;
&nbsp;
   <span style="color: #11740a; font-style: italic;">// Instruct the world to perform a single step of simulation. It is</span>
   <span style="color: #11740a; font-style: italic;">// generally best to keep the time step and iterations fixed.</span>
   world<span style="color: #002200;">-</span>&gt;Step<span style="color: #002200;">&#40;</span>dt, velocityIterations, positionIterations<span style="color: #002200;">&#41;</span>;
&nbsp;
&nbsp;
   <span style="color: #11740a; font-style: italic;">//Iterate over the bodies in the physics world</span>
   <span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span>b2Body<span style="color: #002200;">*</span> b <span style="color: #002200;">=</span> world<span style="color: #002200;">-</span>&gt;GetBodyList<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>; b; b <span style="color: #002200;">=</span> b<span style="color: #002200;">-</span>&gt;GetNext<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
      <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>b<span style="color: #002200;">-</span>&gt;GetUserData<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">!=</span> <span style="color: #a61390;">NULL</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
         <span style="color: #11740a; font-style: italic;">//Synchronize the AtlasSprites position and rotation with the corresponding body</span>
	 CCSprite <span style="color: #002200;">*</span>myActor <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>CCSprite<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>b<span style="color: #002200;">-</span>&gt;GetUserData<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
	 myActor.position <span style="color: #002200;">=</span> CGPointMake<span style="color: #002200;">&#40;</span> b<span style="color: #002200;">-</span>&gt;GetPosition<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>.x <span style="color: #002200;">*</span> PTM_RATIO, 
                                    b<span style="color: #002200;">-</span>&gt;GetPosition<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>.y <span style="color: #002200;">*</span> PTM_RATIO<span style="color: #002200;">&#41;</span>;
	 myActor.rotation <span style="color: #002200;">=</span> <span style="color: #002200;">-</span><span style="color: #2400d9;">1</span> <span style="color: #002200;">*</span> CC_RADIANS_TO_DEGREES<span style="color: #002200;">&#40;</span>b<span style="color: #002200;">-</span>&gt;GetAngle<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;
      <span style="color: #002200;">&#125;</span>	
   <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>ccTouchesEnded<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSSet</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>touches withEvent<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIEvent <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>event <span style="color: #002200;">&#123;</span>
   <span style="color: #11740a; font-style: italic;">//Add a new body/atlas sprite at the touched location</span>
   <span style="color: #a61390;">for</span><span style="color: #002200;">&#40;</span> UITouch <span style="color: #002200;">*</span>touch <span style="color: #a61390;">in</span> touches <span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
      CGPoint location <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>touch locationInView<span style="color: #002200;">:</span> <span style="color: #002200;">&#91;</span>touch view<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
      location <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>CCDirector sharedDirector<span style="color: #002200;">&#93;</span> convertToGL<span style="color: #002200;">:</span> location<span style="color: #002200;">&#93;</span>;
      <span style="color: #002200;">&#91;</span>self addNewSpriteWithCoords<span style="color: #002200;">:</span> location<span style="color: #002200;">&#93;</span>;
   <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>accelerometer<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIAccelerometer<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>accelerometer 
         didAccelerate<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIAcceleration<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>acceleration <span style="color: #002200;">&#123;</span>	
&nbsp;
   <span style="color: #a61390;">static</span> <span style="color: #a61390;">float</span> prevX<span style="color: #002200;">=</span><span style="color: #2400d9;">0</span>, prevY<span style="color: #002200;">=</span><span style="color: #2400d9;">0</span>;
&nbsp;
   <span style="color: #11740a; font-style: italic;">//#define kFilterFactor 0.05f</span>
   <span style="color: #6e371a;">#define kFilterFactor 1.0f	// don't use filter. the code is here just as an example</span>
&nbsp;
   <span style="color: #a61390;">float</span> accelX <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">float</span><span style="color: #002200;">&#41;</span> acceleration.x <span style="color: #002200;">*</span> kFilterFactor <span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span><span style="color: #2400d9;">1</span><span style="color: #002200;">-</span> kFilterFactor<span style="color: #002200;">&#41;</span><span style="color: #002200;">*</span>prevX;
   <span style="color: #a61390;">float</span> accelY <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">float</span><span style="color: #002200;">&#41;</span> acceleration.y <span style="color: #002200;">*</span> kFilterFactor <span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span><span style="color: #2400d9;">1</span><span style="color: #002200;">-</span> kFilterFactor<span style="color: #002200;">&#41;</span><span style="color: #002200;">*</span>prevY;
&nbsp;
   prevX <span style="color: #002200;">=</span> accelX;
   prevY <span style="color: #002200;">=</span> accelY;
&nbsp;
   <span style="color: #11740a; font-style: italic;">// accelerometer values are in &quot;Portrait&quot; mode. Change them to Landscape left</span>
   <span style="color: #11740a; font-style: italic;">// multiply the gravity by 10</span>
   b2Vec2 gravity<span style="color: #002200;">&#40;</span> <span style="color: #002200;">-</span>accelY <span style="color: #002200;">*</span> <span style="color: #2400d9;">10</span>, accelX <span style="color: #002200;">*</span> <span style="color: #2400d9;">10</span><span style="color: #002200;">&#41;</span>;
&nbsp;
   world<span style="color: #002200;">-</span>&gt;SetGravity<span style="color: #002200;">&#40;</span> gravity <span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> dealloc <span style="color: #002200;">&#123;</span>
   <span style="color: #11740a; font-style: italic;">// in case you have something to dealloc, do it in this method</span>
   delete world;
   world <span style="color: #002200;">=</span> <span style="color: #a61390;">NULL</span>;
&nbsp;
   delete m_debugDraw;
&nbsp;
   <span style="color: #11740a; font-style: italic;">// don't forget to call &quot;super dealloc&quot;</span>
   <span style="color: #002200;">&#91;</span>super dealloc<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
<span style="color: #a61390;">@end</span></pre></div></div>


<p><a href="http://feedads.g.doubleclick.net/~a/g4S69cOVoo-Ei5hz8Tq51PO0OSw/0/da"><img src="http://feedads.g.doubleclick.net/~a/g4S69cOVoo-Ei5hz8Tq51PO0OSw/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/g4S69cOVoo-Ei5hz8Tq51PO0OSw/1/da"><img src="http://feedads.g.doubleclick.net/~a/g4S69cOVoo-Ei5hz8Tq51PO0OSw/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.uchidacoonga.com/2011/01/lesson-1-beginning-box2d-physics-engine/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Review of Cocos2d for iPhone 0.99 Beginner’s Guide</title>
		<link>http://www.uchidacoonga.com/2011/01/review-of-cocos2d-for-iphone-0-99-beginners-guide/</link>
		<comments>http://www.uchidacoonga.com/2011/01/review-of-cocos2d-for-iphone-0-99-beginners-guide/#comments</comments>
		<pubDate>Mon, 03 Jan 2011 20:57:51 +0000</pubDate>
		<dc:creator>Min</dc:creator>
				<category><![CDATA[Books]]></category>
		<category><![CDATA[Reviews]]></category>
		<category><![CDATA[Review]]></category>

		<guid isPermaLink="false">http://www.uchidacoonga.com/?p=718</guid>
		<description><![CDATA[Happy New Year everyone! I started off 2011 with a visit to the doctor&#8217;s office. I may as well start the new year on a healthy foot! My New Years resolution is 1. to be healthy (and nag loved ones to lead a more healthy life) and 2. to release a hit iPhone game. I <a href='http://www.uchidacoonga.com/2011/01/review-of-cocos2d-for-iphone-0-99-beginners-guide/'>... [READ THE FULL ARTICLE]</a>]]></description>
			<content:encoded><![CDATA[<p>Happy New Year everyone! I started off 2011 with a visit to the doctor&#8217;s office. I may as well start the new year on a healthy foot! My New Years resolution is 1. to be healthy (and nag loved ones to lead a more healthy life) and 2. to release a hit iPhone game. I also had a chance to read through the new book on Cocos2d that I mentioned in my previous blog post. </p>
<p>I <a href="http://www.uchidacoonga.com/2010/12/book-preview-cocos2d-for-iphone-0-99-beginners-guide/screen-shot-2010-12-23-at-3-15-31-am/" rel="attachment wp-att-711"><img src="http://www.uchidacoonga.com/wp-content/uploads/2010/12/Screen-shot-2010-12-23-at-3.15.31-AM.png" alt="" title="Screen shot 2010-12-23 at 3.15.31 AM" width="127" height="155" class="alignleft size-full wp-image-711" /></a>recently discovered a program that enables non-programmers to author iPhone games using a drag and drop interface, without nary a worry about programming. It will make about 60-70% of the easy stuff very easy to do, but the remaining 30-40% is probably painful to achieve without a lot of workarounds &#8212; workarounds that would have been unnecessary if you had programmed it instead. I will say that it is probably great for the simple stuff and for rapid prototyping. </p>
<p>On the other end spectrum are those who are a glutton for pain and insist on doing everything from scratch. If you are making a game on the iPhone, this usually means delving into the mysteries of OpenGL ES. My salute to those brave souls who travel the path less traveled by, but for mere mortals such as myself, I would opt for the middle-way and use a robust and mature library like Cocos2d.</p>
<p>Cocos2d is a wonderful 2d game library. The blood of OpenGL ES is flowing rigorously underneath the hood so you get the performance benefits of OpenGL ES while being shielded from having to touch it directly. To date, there are thousands of games made with Cocos2d, including many of the top free and paid games on the Apple App store.</p>
<p>It can be a daunting task to learn anything related to game programming if you have never attempted it before. It is as much a science as it is an art. And with an open source library such as Cocos2d, it is that much more important for a mentor to hold your hand and show you the way to the path of enlightenment. Notice I said to the &#8220;path&#8221; of enlightenment and not to enlightenment itself. That task belongs to only you! There are not too many books on the subject in the market, and the book <a href="http://link.packtpub.com/lbMSbv">Cocos2d for iPhone 0.99 Beginner&#8217;s Guide</a> is a welcome addition to any aspiring iPhone game programmer&#8217;s library.</p>
<p>As the title of the book suggests, the author assumes that the reader is a beginning game developer (not necessarily a beginning iPhone developer). The book will take you through building 3 complete iPhone games, each of which is of a different genre. The first game is a puzzle, the second a vertical shooter, and the third is a physics based game using the Chipmunk physics engine. Readers will be able to take away useful information from each of these games, as different genre of games will require a different mentality and programming skill set. The author also lists some links to games that come with complete source code, which I found very useful as well.</p>
<p>It will give you a fairly complete overview of the Cocos2d engine. The chapters are organized in a logical manner, and each chapter builds on the previous chapters. I particularly liked the chapter about the particle system in Cocos2d. Readers will also appreciate the fact that the author introduces the tools that are commonly used by Cocos2d programmers. These tools will prove to be an invaluable time saver, and you will immediately recognize the benefits of using them. </p>
<p>The book is written in a fairly clear manner and does a good job of explaining the code. For example, just when you start to feel lost, you will be happy to run across sections titled &#8220;What Just Happened?&#8221; that will explain the code for you in plain English. </p>
<p>It did, however, seem slightly rushed. I also did not particularly care for the formatting of the source code in the book and wished more care was taken with them. It must be noted that I reviewed the PDF version of the book, so I cannot speak for the printed version. These imperfections only slightly mar the usefulness of the book. And those just starting out with Cocos2d will certainly learn a great deal from the book, which is the target demographic of the book (as it is obvious and evident from the title of the book).</p>

<p><a href="http://feedads.g.doubleclick.net/~a/GyvSFqEmbwRu4HHYmlPhJ6g2D1U/0/da"><img src="http://feedads.g.doubleclick.net/~a/GyvSFqEmbwRu4HHYmlPhJ6g2D1U/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/GyvSFqEmbwRu4HHYmlPhJ6g2D1U/1/da"><img src="http://feedads.g.doubleclick.net/~a/GyvSFqEmbwRu4HHYmlPhJ6g2D1U/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.uchidacoonga.com/2011/01/review-of-cocos2d-for-iphone-0-99-beginners-guide/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Book Preview: Cocos2d for iPhone 0.99 Beginner’s Guide</title>
		<link>http://www.uchidacoonga.com/2010/12/book-preview-cocos2d-for-iphone-0-99-beginners-guide/</link>
		<comments>http://www.uchidacoonga.com/2010/12/book-preview-cocos2d-for-iphone-0-99-beginners-guide/#comments</comments>
		<pubDate>Thu, 23 Dec 2010 07:57:32 +0000</pubDate>
		<dc:creator>Min</dc:creator>
				<category><![CDATA[Books]]></category>
		<category><![CDATA[Reviews]]></category>
		<category><![CDATA[Review]]></category>

		<guid isPermaLink="false">http://www.uchidacoonga.com/?p=704</guid>
		<description><![CDATA[I have been contacted by Packt Publishing to review a new book on game programming on the iPhone with Cocos2d titled Cocos2d for iPhone 0.99 Beginner&#8217;s Guide. I will be reviewing the book in a future post, but in the mean time, please check out the sample chapters. There are not too many books on <a href='http://www.uchidacoonga.com/2010/12/book-preview-cocos2d-for-iphone-0-99-beginners-guide/'>... [READ THE FULL ARTICLE]</a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.uchidacoonga.com/2010/12/book-preview-cocos2d-for-iphone-0-99-beginners-guide/screen-shot-2010-12-23-at-3-15-31-am/" rel="attachment wp-att-711"><img src="http://www.uchidacoonga.com/wp-content/uploads/2010/12/Screen-shot-2010-12-23-at-3.15.31-AM.png" alt="" title="Screen shot 2010-12-23 at 3.15.31 AM" width="127" height="155" class="alignleft size-full wp-image-711" /></a>I have been contacted by <a href="http://www.packtpub.com">Packt Publishing</a> to review a new book on game programming on the iPhone with Cocos2d titled <a href="http://link.packtpub.com/lbMSbv">Cocos2d for iPhone 0.99 Beginner&#8217;s Guide</a>. I will be reviewing the book in a future post, but in the mean time, please check out the <a href="https://www.packtpub.com/sites/default/files/3166OS-Chapter-5-Surfing-through-Scenes.pdf">sample chapters</a>. There are not too many books on the subject, and it looks to be a great addition to an aspiring game programmer&#8217;s library. Please subscribe to my RSS feed or check back later for a detailed review of the book. Here is the press release for the book.</p>
<h4><span style="color: #ff6600;"><strong>Make captivating games for the iPhone using Packt&#8217;s new book on Cocos2d</strong></span></h4>
<p>Packt is pleased to announce Cocos2d for iPhone 0.99 Beginner&#8217;s Guide, a new book which helps in building fun and exciting iPhone games using the cocos2d for iPhone framework. Written by Pablo Ruiz, this book will help programmers make their first iPhone game in no time. </p>
<p>Cocos2d for iPhone is a robust but simple-to-use game framework for building 2D games, demos, and other graphical/interactive applications for the iPhone. Its API comes integrated with Box2D and Chipmunk physics engines. Being an open source platform, it is compatible both with closed and open source games. Over 1500 AppStore games have been built with cocos2d for iPhone.</p>
<p>Cocos2d for iPhone 0.99 Beginner&#8217;s Guide explains in detail, all the key concepts of the iPhone framework and game programming required for readers to build their very first iPhone game. Readers will learn to add animations, sounds, and particle effects to their games which will help enhance their games with a lot of cool features and eye candy while making the game behave realistically using a physics engine.</p>
<p>This book is filled with illustrations, diagrams, and tips for building iPhone games, with clear step-by-step instructions and practical examples. It covers basic features such as sprites, actions, menu design creation and also helps readers utilize Cocos2d for pasting labels, integrating it with Social Networks and surfing through scenes, layers and transitions. </p>
<p>Seasoned and beginner programmers with a desire to enter the iPhone industry, who possess some basic programming experience with Objective-C and a good understanding of OOP, will find this book to be an interesting and beneficial read. The book is out now and available from Packt. For more information please visit: -<br />
<a href="http://www.packtpub.com/cocos2d-games-for-iphone-0-99-beginners-guide/book">www.packtpub.com/cocos2d-games-for-iphone-0-99-beginners-guide/book</a></p>

<p><a href="http://feedads.g.doubleclick.net/~a/VIFe0W67hKvfpiZPpZYaG_UO4Tg/0/da"><img src="http://feedads.g.doubleclick.net/~a/VIFe0W67hKvfpiZPpZYaG_UO4Tg/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/VIFe0W67hKvfpiZPpZYaG_UO4Tg/1/da"><img src="http://feedads.g.doubleclick.net/~a/VIFe0W67hKvfpiZPpZYaG_UO4Tg/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.uchidacoonga.com/2010/12/book-preview-cocos2d-for-iphone-0-99-beginners-guide/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Tips on Reducing Memory Usage and Avoiding didReceiveMemoryWarning</title>
		<link>http://www.uchidacoonga.com/2010/12/tips-on-reducing-memory-usage-and-avoiding-didreceivememorywarning/</link>
		<comments>http://www.uchidacoonga.com/2010/12/tips-on-reducing-memory-usage-and-avoiding-didreceivememorywarning/#comments</comments>
		<pubDate>Tue, 21 Dec 2010 17:50:05 +0000</pubDate>
		<dc:creator>Min</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[iPhone Development]]></category>
		<category><![CDATA[Objective-C]]></category>

		<guid isPermaLink="false">http://www.uchidacoonga.com/?p=683</guid>
		<description><![CDATA[Although it has gotten better with the new generation of the iPhone, programmers must continue to be vigilant when it comes to memory usage if they want to avoid their applications crashing mysteriously. The best way to avoid the didReceiveMemoryWarning is to minimize memory usage from the get-go. Safest sex being abstinence and all that&#8230; <a href='http://www.uchidacoonga.com/2010/12/tips-on-reducing-memory-usage-and-avoiding-didreceivememorywarning/'>... [READ THE FULL ARTICLE]</a>]]></description>
			<content:encoded><![CDATA[<p>Although it has gotten better with the new generation of the iPhone, programmers must continue to be vigilant when it comes to memory usage if they want to avoid their applications crashing mysteriously. The best way to avoid the didReceiveMemoryWarning is to minimize memory usage from the get-go. Safest sex being abstinence and all that&#8230; eh? <img src='http://www.uchidacoonga.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  </p>
<h4><span style="color: #ff6600;"><strong>Tip 1: Do not use UIImage imageNamed: method</strong></span></h4>
<p>UIImage&#8217;s imageNamed method caches the image. This is a handy feature that can beneficial, but depending on your needs, it may be better for you to manage the cache yourself. For example, if you are loading huge images that do not get used often, then it would be better for you to release the image after each use. I would suggest extending UIImage with a new method that does not cache the image like this:</p>
<p>The header file:</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &lt;Foundation/Foundation.h&gt;</span>
<span style="color: #a61390;">@interface</span> UIImage <span style="color: #002200;">&#40;</span>DoNotCache<span style="color: #002200;">&#41;</span>
<span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span>UIImage <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>newImageNotCached<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>filename;
<span style="color: #a61390;">@end</span></pre></div></div>

<p>The implementation file:</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">@implementation</span> UIImage <span style="color: #002200;">&#40;</span>DoNotCache<span style="color: #002200;">&#41;</span>
<span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span>UIImage <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>newImageNotCached<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>filename <span style="color: #002200;">&#123;</span>
    <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>imageFile <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSString</span> alloc<span style="color: #002200;">&#93;</span> initWithFormat<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;%@/%@&quot;</span>, <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSBundle</span> mainBundle<span style="color: #002200;">&#93;</span> resourcePath<span style="color: #002200;">&#93;</span>, filename<span style="color: #002200;">&#93;</span>;
    UIImage <span style="color: #002200;">*</span>image <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIImage alloc<span style="color: #002200;">&#93;</span> initWithContentsOfFile<span style="color: #002200;">:</span>imageFile<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>imageFile release<span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">return</span> image;
<span style="color: #002200;">&#125;</span>
<span style="color: #a61390;">@end</span></pre></div></div>

<p>This way, you have complete control over the memory used by your images. You can then cache these images into a NSMutableArray and then release them when you no longer need them.</p>
<h4><span style="color: #ff6600;"><strong>Tip 2: Break out your views into separate XIB / NIB files</strong></span></h4>
<p>If your view can be separated into multiple views, then create a separate UIViewController for each of them. This way, you can unload the views when not needed, instead of it consuming valuable memory even when they&#8217;re not visible. So always think about how your view can be separated into multiple views that can be loaded lazily.</p>
<h4><span style="color: #ff6600;"><strong>Tip 3: Manually trigger didReceiveMemoryWarning</strong></span></h4>
<p>You can manually trigger didReceiveMemoryWarning from the simulator so make sure to test it in the simulator! The option is under <i>Hardware / Simulate Memory Warning</i>. </p>
<h4><span style="color: #ff6600;"><strong>Tip 4: Use a local NSAutoRelease Pool</strong></span></h4>
<p>If you are autoreleasing lot of objects, you may run into situations where your objects may not be released until your program terminates. If so, think about using a local autorelease pool. Autorelease pools are staked, so if you create a new autorelease pool, it gets inserted into the top of the stack.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #400080;">NSAutoreleasePool</span> <span style="color: #002200;">*</span>pool <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSAutoreleasePool</span> alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
<span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span><span style="color: #a61390;">string</span> <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSString</span> alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span> autorelease<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>pool drain<span style="color: #002200;">&#93;</span>;</pre></div></div>

<h4><span style="color: #ff6600;"><strong>Tip 5: Be mindful of container classes retaining and releasing objects</strong></span></h4>
<p>Pay attention to whether the library class you are using is retaining or releasing your objects. For example, when you add an object into a NSMutableArray, it is automatically retained. So you want to send the object that you are adding a release message to avoid memory leaks.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #400080;">NSMutableArray</span> <span style="color: #002200;">*</span>array <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSMutableArray</span> alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// obj has retain count of +1</span>
MyObject <span style="color: #002200;">*</span>obj <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>MyObject alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// obj has retain count of +2, so make sure to release it</span>
<span style="color: #002200;">&#91;</span>array addObject<span style="color: #002200;">:</span>array<span style="color: #002200;">&#93;</span>;     
&nbsp;
<span style="color: #11740a; font-style: italic;">// obj has retain count of +1</span>
<span style="color: #002200;">&#91;</span>obj release<span style="color: #002200;">&#93;</span>;</pre></div></div>

<p>This also means when you remove an object from the array, it will automatically be released. If you are not sure whether the method you are calling is retaining or releasing, then make sure to look up the documentation for that peace of mind.</p>
<p>Also check out my original entry titled <a href="http://www.uchidacoonga.com/?p=383">Handling didReceiveMemoryWarning</a>. </p>

<p><a href="http://feedads.g.doubleclick.net/~a/JKIfqR46jzRCVhkCivE6YK0jLvw/0/da"><img src="http://feedads.g.doubleclick.net/~a/JKIfqR46jzRCVhkCivE6YK0jLvw/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/JKIfqR46jzRCVhkCivE6YK0jLvw/1/da"><img src="http://feedads.g.doubleclick.net/~a/JKIfqR46jzRCVhkCivE6YK0jLvw/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.uchidacoonga.com/2010/12/tips-on-reducing-memory-usage-and-avoiding-didreceivememorywarning/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CCSprite addAnimation is deprecated in Cocos2D 0.99.5</title>
		<link>http://www.uchidacoonga.com/2010/12/ccsprite-addanimation-is-deprecated-in-cocos2d-0-99-5/</link>
		<comments>http://www.uchidacoonga.com/2010/12/ccsprite-addanimation-is-deprecated-in-cocos2d-0-99-5/#comments</comments>
		<pubDate>Fri, 17 Dec 2010 22:01:01 +0000</pubDate>
		<dc:creator>Min</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[iPhone Development]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Cocos2D]]></category>

		<guid isPermaLink="false">http://www.uchidacoonga.com/?p=666</guid>
		<description><![CDATA[While playing around with various sample codes downloaded from the interwebs, I noticed that the addAnimation method of CCSprite has been deprecated. Though it continues to compile and run without a hitch, my OCD comes to the rescue. If you refer to the API reference for version 0.99.5 of Cocos2D (here if anyone is interested), <a href='http://www.uchidacoonga.com/2010/12/ccsprite-addanimation-is-deprecated-in-cocos2d-0-99-5/'>... [READ THE FULL ARTICLE]</a>]]></description>
			<content:encoded><![CDATA[<p>While playing around with various sample codes downloaded from the interwebs, I noticed that the addAnimation method of CCSprite has been deprecated. Though it continues to compile and run without a hitch, my OCD comes to the rescue. If you refer to the API reference for version 0.99.5 of Cocos2D (<a href="http://www.cocos2d-iphone.org/api-ref/0.99.5/annotated.html">here if anyone is interested</a>), you will notice that it says &#8220;Deprecated: Use CCAnimationCache instead. Will be removed in 1.0.1&#8243;.</p>
<h4><span style="color: #ff6600;"><strong>So let&#8217;s use CCAnimationCache!</strong></span></h4>
<p>So let&#8217;s say that you have a class derived from CCSprite for each game object, and that you load the animations for the game object during initialization by calling CCSprite addAnimation. Now you&#8217;ll have to change it to use CCAnimationCache instead. It&#8217;s pretty simple. Note that I only load the animation into the cache once by checking a boolean variable to see if it has already been loaded. I do this because there can be many instances of the game object on the screen at once (imagine bullets), and the application would crash if you tried to load the same animation twice. You could initialize the animation outside of your game object, but if you wanted to initialize it when your game object is instantiated, just remember to load it once as it is done here.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">@implementation</span> SomeGameObject 
<span style="color: #a61390;">static</span> <span style="color: #a61390;">BOOL</span> animationLoaded <span style="color: #002200;">=</span> <span style="color: #a61390;">NO</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// Some other code...</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> initializeAnimations <span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">NO</span> <span style="color: #002200;">==</span> animationLoaded<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        animationLoaded <span style="color: #002200;">=</span> <span style="color: #a61390;">YES</span>;
        CCAnimation <span style="color: #002200;">*</span>anim1 <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>CCAnimation animationWithFrames<span style="color: #002200;">:</span>some_array1<span style="color: #002200;">&#93;</span>;
        <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>CCAnimationCache sharedAnimationCache<span style="color: #002200;">&#93;</span> addAnimation<span style="color: #002200;">:</span>anim1 name<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;anim1&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
        CCAnimation <span style="color: #002200;">*</span>anim2 <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>CCAnimation animationWithFrames<span style="color: #002200;">:</span>some_array2<span style="color: #002200;">&#93;</span>;
        <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>CCAnimationCache sharedAnimationCache<span style="color: #002200;">&#93;</span> addAnimation<span style="color: #002200;">:</span>anim2 name<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;anim2&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
        CCAnimation <span style="color: #002200;">*</span>anim3 <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>CCAnimation animationWithFrames<span style="color: #002200;">:</span>some_array3<span style="color: #002200;">&#93;</span>;
        <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>CCAnimationCache sharedAnimationCache<span style="color: #002200;">&#93;</span> addAnimation<span style="color: #002200;">:</span>anim3 name<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;anim1&quot;</span><span style="color: #002200;">&#93;</span>;   
    <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span>
<span style="color: #a61390;">@end</span></pre></div></div>

<p>Then when you are ready to use the animation, it&#8217;s simple to retrieve them by name like so:</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;">CCAnimation <span style="color: #002200;">*</span>anim1 <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>CCAnimationCache sharedAnimationCache<span style="color: #002200;">&#93;</span> animationByName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;anim1&quot;</span><span style="color: #002200;">&#93;</span>;
CCAnimation <span style="color: #002200;">*</span>anim2 <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>CCAnimationCache sharedAnimationCache<span style="color: #002200;">&#93;</span> animationByName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;anim2&quot;</span><span style="color: #002200;">&#93;</span>;
CCAnimation <span style="color: #002200;">*</span>anim3 <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>CCAnimationCache sharedAnimationCache<span style="color: #002200;">&#93;</span> animationByName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;anim3&quot;</span><span style="color: #002200;">&#93;</span>;</pre></div></div>

<p>Hope this simple tip was helpful to someone. Happy coding!</p>

<p><a href="http://feedads.g.doubleclick.net/~a/-n4-rHDpew11qhlvOyg8ywQtZ8c/0/da"><img src="http://feedads.g.doubleclick.net/~a/-n4-rHDpew11qhlvOyg8ywQtZ8c/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/-n4-rHDpew11qhlvOyg8ywQtZ8c/1/da"><img src="http://feedads.g.doubleclick.net/~a/-n4-rHDpew11qhlvOyg8ywQtZ8c/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.uchidacoonga.com/2010/12/ccsprite-addanimation-is-deprecated-in-cocos2d-0-99-5/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss><!-- Dynamic page generated in 6.619 seconds. --><!-- Cached page generated by WP-Super-Cache on 2012-02-18 22:55:03 -->

