<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	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/"
	>

<channel>
	<title>Allan Bishop&#039;s Developer Blog</title>
	<atom:link href="http://blog.allanbishop.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.allanbishop.com</link>
	<description>Development of interactive media</description>
	<lastBuildDate>Wed, 09 May 2012 11:21:50 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Box2D 2.1a &#8220;Rope Joint&#8221; ported to AS3</title>
		<link>http://blog.allanbishop.com/box2d-2-1a-rope-joint-ported-to-as3/</link>
		<comments>http://blog.allanbishop.com/box2d-2-1a-rope-joint-ported-to-as3/#comments</comments>
		<pubDate>Wed, 09 May 2012 10:32:32 +0000</pubDate>
		<dc:creator>Allan Bishop</dc:creator>
				<category><![CDATA[Box2D]]></category>

		<guid isPermaLink="false">http://blog.allanbishop.com/?p=673</guid>
		<description><![CDATA[You may have noticed that the original C++ version of Box2D is now up to version 2.2.1. As of version 2.2.0 there were a few additions, one of which being a b2RopeJoint. For ActionScript 3.0 users the only choice to incorporate this feature was to use the Alchemy generated Box2D port. Developers using Box2DFlashAS3 by BorisTheBrave [...]]]></description>
			<content:encoded><![CDATA[<p><a title="Box2D 2.1a Tutorial - Part 2 Joints" href="http://blog.allanbishop.com/box2d-2-1a-tutorial-part-2-joints/" target="_blank"><img class="aligncenter size-full wp-image-674" title="Box2DRopeJointAS3" src="http://blog.allanbishop.com/wp-content/uploads/2012/05/Box2DBlogPostRopeFinal.png" alt="Box2D 2.1a Rope Joint for AS3" width="640" height="380" /></a></p>
<p>You may have noticed that the original C++ version of Box2D is now up to version <em>2.2.1</em>. As of version <em>2.2.0</em> there were a few additions, one of which being a <strong>b2RopeJoint</strong>. For ActionScript 3.0 users the only choice to incorporate this feature was to use the <em>Alchemy</em> generated Box2D port. Developers using <em>Box2DFlashAS3</em> by BorisTheBrave unfortunately did not have this as the port is of version <em>2.1a</em>. That is, until now.</p>
<p><span id="more-673"></span>Because I am using the HaXe version of Box2D which is based off the <em>Box2DFlashAS3</em> I needed it, and, from my searches on the internet, there seemed to be a few people who were still using <em>Box2DFlashAS3</em> but wanted the Rope Joint. Hopefully this will help those people out. I have also updated my joints <a title="Box2D 2.1a Tutorial - part 2 Joints" href="http://blog.allanbishop.com/box2d-2-1a-tutorial-part-2-joints/" target="_blank">tutorial</a> to incorporate the rope joint.</p>
<p><strong>Installation instructions:</strong> Save these files into the <em>Box2D\Dynamics\Joints</em> folder. b2Joint will overwrite the existing b2Joint.</p>
<p><a href="http://blog.allanbishop.com/wp-content/uploads/2012/05/b2RopeJoint.as">b2RopeJoint</a></p>
<p><a href="http://blog.allanbishop.com/wp-content/uploads/2012/05/b2RopeJointDef.as">b2RopeJointDef</a></p>
<p><a href="http://blog.allanbishop.com/wp-content/uploads/2012/05/b2Joint.as">b2Joint</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.allanbishop.com/box2d-2-1a-rope-joint-ported-to-as3/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>HaXe &amp; NME tutorial: Install and setup on Mac OS X</title>
		<link>http://blog.allanbishop.com/haxe-nme-tutorial-install-and-setup-on-mac-os-x/</link>
		<comments>http://blog.allanbishop.com/haxe-nme-tutorial-install-and-setup-on-mac-os-x/#comments</comments>
		<pubDate>Thu, 01 Mar 2012 12:56:05 +0000</pubDate>
		<dc:creator>Allan Bishop</dc:creator>
				<category><![CDATA[NME]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://blog.allanbishop.com/?p=652</guid>
		<description><![CDATA[In the previous screencast I showed how to install and setup HaXe and NME on a Windows 7 machine and compile to Flash and Android. This time I will demonstrate how to install and setup HaXe with NME on a Mac OS X machine and compile an open source project called BunnyMark to the iOS [...]]]></description>
			<content:encoded><![CDATA[<p><object width="560" height="315"><param name="movie" value="http://www.youtube.com/v/5Jw9a3ti8wQ?version=3&amp;hl=en_GB"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/5Jw9a3ti8wQ?version=3&amp;hl=en_GB" type="application/x-shockwave-flash" width="560" height="315" allowscriptaccess="always" allowfullscreen="true"></embed></object></p>
<p>In the previous screencast I showed how to install and setup HaXe and NME on a Windows 7 machine and compile to Flash and Android. This time I will demonstrate how to install and setup HaXe with NME on a Mac OS X machine and compile an open source project called <a href="https://github.com/elsassph/nme-bunnymark" target="_blank">BunnyMark</a> to the iOS simulator in Xcode.</p>
<p>Note that you can only compile for the iOS on a Mac OS X as the compiler generates an Xcode project that Xcode then compiles.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.allanbishop.com/haxe-nme-tutorial-install-and-setup-on-mac-os-x/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>HaXe &amp; NME tutorial: Install and setup on Windows</title>
		<link>http://blog.allanbishop.com/haxe-nme-tutorial-install-and-setup-on-windows/</link>
		<comments>http://blog.allanbishop.com/haxe-nme-tutorial-install-and-setup-on-windows/#comments</comments>
		<pubDate>Mon, 20 Feb 2012 13:04:46 +0000</pubDate>
		<dc:creator>Allan Bishop</dc:creator>
				<category><![CDATA[NME]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://blog.allanbishop.com/?p=565</guid>
		<description><![CDATA[If you have read my last post then you will know that I am endeavouring to increase my focus on mobile development. This lead to one reader mentioning an API called NME that allows code written in HaXe (very similar to AS3) to cross compile natively to Flash, Android, iOS, webOS, Windows, Mac, Linux, and [...]]]></description>
			<content:encoded><![CDATA[<p><object width="560" height="315" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowFullScreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="http://www.youtube.com/v/wsSVoKiCuQQ?version=3&amp;hl=en_GB&amp;rel=0" /><param name="allowfullscreen" value="true" /><embed width="560" height="315" type="application/x-shockwave-flash" src="http://www.youtube.com/v/wsSVoKiCuQQ?version=3&amp;hl=en_GB&amp;rel=0" allowFullScreen="true" allowscriptaccess="always" allowfullscreen="true" /></object></p>
<p>If you have read my last post then you will know that I am endeavouring to increase my focus on mobile development. This lead to one reader mentioning an API called <a title="NME" href="http://www.haxenme.org/" target="_blank">NME </a>that allows code written in <a title="HaXe" href="http://haxe.org/" target="_blank">HaXe </a>(very similar to AS3) to cross compile natively to Flash, Android, iOS, webOS, Windows, Mac, Linux, and HTML5 targets.</p>
<p>As the code is natively compiled (c++ for Android and iOS) the performance is perfectly acceptable for physics based games. This is in contrast to<a title="Adobe Air's export to Android and iOS" href="http://www.adobe.com/devnet/air/articles/packaging-air-apps.html" target="_blank"> Adobe Air&#8217;s export to Android and iOS</a> that has a Virtual Machine interpreting the code thereby causing poor performance.</p>
<p>So far I have ported a couple of earlier Box2D tutorials and successfully ran them on my Android phone at a smooth frame rate. I was also able to get it working well with the iOS simulator.</p>
<p>If you are interested in programming with NME then I thought I would post a screencast tutorial to demonstrate how to install and setup HaXe with NME and compile a simple HelloWorld application to Android and Flash.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.allanbishop.com/haxe-nme-tutorial-install-and-setup-on-windows/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>What&#8217;s coming in 2012</title>
		<link>http://blog.allanbishop.com/whats-coming-in-2012/</link>
		<comments>http://blog.allanbishop.com/whats-coming-in-2012/#comments</comments>
		<pubDate>Mon, 30 Jan 2012 06:12:39 +0000</pubDate>
		<dc:creator>Allan Bishop</dc:creator>
				<category><![CDATA[News]]></category>

		<guid isPermaLink="false">http://blog.allanbishop.com/?p=557</guid>
		<description><![CDATA[Being a new year (as well as a being a while since my last post) I thought I would let you know what I have been working on and what content you can expect to see on this blog in 2012. For the past six months I have been working on a 2D game engine [...]]]></description>
			<content:encoded><![CDATA[<p><img class="aligncenter size-full wp-image-560" title="AndroidPhotoshop" src="http://blog.allanbishop.com/wp-content/uploads/2012/01/AndroidPhotoshop.png" alt="" width="640" height="380" /></p>
<p>Being a new year (as well as a being a while since my last post) I thought I would let you know what I have been working on and what content you can expect to see on this blog in 2012.</p>
<p>For the past six months I have been working on a 2D game engine that I have developed from scratch. The goal of this engine is to allow absolute freedom and ease in creating game content. So far I am pleased with the results of it, even if it is quite rough around the edges.</p>
<p>Without going into too much detail of the engine, it is based on a <em>Component Based Entity System </em>architecture<em>. </em>I have found using such a system allows for more freedom at the game logic layer and makes game changes easier to implement. Expect to see a few posts coming up explaining the architecture, the benefits and how I used it in my game engine.</p>
<p>Of course with all this game engine programming I have been using  Box2D  to power the physics and so have been experimenting with it. One of my aims was to to create a rope in the Box2D world, for which Box2D is notoriously difficult to get right. My latest creation is a climbable rope to go alongside my shooting out rope. Again, expect to see a few posts on this as well as other bits and pieces to do with Box2D.</p>
<p>In other news, you may be aware Adobe has pulled out of supporting Android devices with Flash Player. I feel that this unfortunately signals the decline/end of the Flash player. Rather than being too dismayed about this, instead, I see this as an opportunity for me to branch out and increase my skill set.</p>
<p>The first technology in my cross hairs to learn is Android development. With the marketshare of the Android platform increasing, the open nature of the development environment, as well as the similarity of Java to ActionScript 3.0 it looks like an exciting platform to target. This means that you can expect to find more Android related tutorials popping up here, including a Flash to Android tutorial series!</p>
<p>So 2012 is shaping up as a big, challenging, and exciting year!</p>
<p>Hope you enjoy.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.allanbishop.com/whats-coming-in-2012/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Box 2D 2.1a Tutorial – Part 10 (Fixed time step)</title>
		<link>http://blog.allanbishop.com/box-2d-2-1a-tutorial-part-10-fixed-time-step/</link>
		<comments>http://blog.allanbishop.com/box-2d-2-1a-tutorial-part-10-fixed-time-step/#comments</comments>
		<pubDate>Fri, 25 Nov 2011 01:39:09 +0000</pubDate>
		<dc:creator>Allan Bishop</dc:creator>
				<category><![CDATA[Box2D]]></category>
		<category><![CDATA[Physics]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://blog.allanbishop.com/?p=531</guid>
		<description><![CDATA[So far, in each tutorial, we have been calling the step function on each frame update with a fixed delta time to apply the physics. This works quite well as we have seen. However, there is a problem with this approach. While we may be targeting a frame rate of say 60fps, there is no [...]]]></description>
			<content:encoded><![CDATA[<p><img class="aligncenter size-full wp-image-541" title="Box2D Fixed time step" src="http://blog.allanbishop.com/wp-content/uploads/2011/11/FixedTimeStep.jpg" alt="Box2D Fixed time step" width="640" height="380" /><br />
So far, in each tutorial, we have been calling the step function on each frame update with a fixed delta time to apply the physics. This works quite well as we have seen.</p>
<p>However, there is a problem with this approach. While we may be targeting a frame rate of say 60fps, there is no guarantee that it will update that frequently. A user’s computer hardware may cause it to run slower or faster than this, and subsequently, the physics simulation may appear to run either in slow motion or to appear sped up.</p>
<p>So if you are finding this a problem in your game how can we go about fixing this? The answer is to separate the physics update from our game loop so the physics is not dependant on how often the game loop is called.<span id="more-531"></span></p>
<p>While there are a few ways we might want to achieve this, we have to consider the effects of the various implementations. For example, it would be fair to assume that instead of passing in a fixed delta to the step function, that we instead could measure the time it takes per frame for the game loop to be called, and based on this value, call the step function.</p>
<p>Unfortunately, there are a few problems with this approach. The main reason is that the size of the delta can significantly affect the physics engine. Simply, if it is too big, then the engine will exhibit all sorts of bizarre behaviour. Remember, in the real world physics is continuous, but in a computer simulation we don’t have such luxury so ideally we want to call the physics update as quickly as possible. Additionally, the simulation is no longer deterministic. That is, it is no longer predictable, so if we were to create a scene involving a few box2D bodies and apply some predetermined force, then each time we run the game, the resulting collisions would be slightly different.</p>
<p>This would make it impossible to accurately implement a replay function, or to set up some scene and ensure the outcome of applying forces will always be the same.</p>
<p>To solve this, we have to ensure that we don’t use a variable delta time for updating the step function, but that leaves us back to where we started. The trick is, that instead of calling the step function once per frame update, we call it a variable amount of times, depending on how long the games update loop takes.</p>
<p>There is a detailed explanation of the algorithm at <a href="http://gafferongames.com/game-physics/fix-your-timestep/" target="_blank">http://gafferongames.com/game-physics/fix-your-timestep/ </a></p>
<p>However, to save you some time, and also to serve as an alternative explanation, I will demonstrate the concept behind the algorithm using an example:</p>
<p>Underneath are the blocks that represent the time it takes per game loop. In a perfect world we would ideally want each loop to take 0.01666666 seconds to then be exactly  60 frames per second. But as you can see, the first loop is a little slower and takes 0.021 seconds. So we know that we can step at least once and have a little bit of a remainder left. So what do we do with this remainder? We could store this value and add the time to the next frame time for when we divide by the fixed rate. However, this causes what is known as temporal aliasing, a stuttering of the rendering due to the render and physics being out of sync.</p>
<p><img class="aligncenter size-full wp-image-550" title="Fixed time step diagram" src="http://blog.allanbishop.com/wp-content/uploads/2011/11/FixedTimeStepDiagram1.png" alt="Fixed time step diagram" width="642" height="382" /></p>
<p>An analogy would be to imagine a car with a fast constant velocity. If at time = k it does 2 steps and renders but then at time=k+1 it does 4 steps, then it won’t appear very smooth.<br />
Therefore, with this remainder, we instead use whatever is left as a ratio of how far we are to the next physics state. So if we know the position of a body is [2,3] and the next state it is [4,5] and the ratio is 0.5, then we can figure out that the graphics should be rendered at [3,4].</p>
<p>But how do we know what the next state is? We don’t. That leaves us with two choices. Either predict what the next state might be (extrapolation), or, ideally, we run the loop and take the last state and the state before that as the two states (interpolation). Then we use the ratio on this. Of course, this means the renderer will always be 1 frame behind the physics but this should not be a problem. You can find a more detailed explanation at <a href="http://www.unagames.com/blog/daniele/2010/06/fixed-time-step-implementation-box2d" target="_blank">http://www.unagames.com/blog/daniele/2010/06/fixed-time-step-implementation-box2d</a>. I have also gone and ported over their code into ActionScript 3.0 which you can find below.</p>
<pre class="brush: as3; title: ; notranslate">
private var _currentTime:Number = GameTimer.getVirtualTime() / 1000; //your implementation here may differ
private const FIXED_TIMESTEP:Number = 1 / 60;
private var fixedTimestepAccumulator:Number = 0;
private var fixedTimestepAccumulatorRatio:Number = 0;
private var velocityIterations:int = 8;
private var positionIterations:int = 1;

public function process():void
{
	var newTime:Number = GameTimer.getVirtualTime() / 1000;
	var dt:Number = newTime - _currentTime;
	_currentTime = newTime;

	const MAX_STEPS:int = 5;
	fixedTimestepAccumulator += dt;
	const nSteps:int = Math.floor(fixedTimestepAccumulator / FIXED_TIMESTEP);

	if (nSteps &gt; 0)
	{
		fixedTimestepAccumulator -= nSteps * FIXED_TIMESTEP;
	}
	fixedTimestepAccumulatorRatio = fixedTimestepAccumulator / FIXED_TIMESTEP;
	const nStepsClamped:int = min(nSteps, MAX_STEPS);

	for (var i:int = 0; i &lt; nStepsClamped; ++i)
	{
		resetSmoothStates();
		singleStep(FIXED_TIMESTEP);
	}
	world.ClearForces();
	smoothStates();
}
</pre>
<p>Our singleStep function has to do a few things that depends on how you have set up the rest of your system so I can&#8217;t supply you with copy n paste code. Before the world.Step function is called, you will want to apply the various forces to the world bodies to ensure constant speed of objects regardless of the render frame rate. Same goes for polling of key inputs.<br />
After the world.Step function is called you will also want to process any collisions.</p>
<pre class="brush: as3; title: ; notranslate">
private function singleStep(dt:Number):void
{
	//TODO apply physics forces, poll inputs etc
	world.Step(dt, velocityIterations, positionIterations);
	//TODO process collisions
}
</pre>
<p>The following code will again depend on how you have set up your game so don&#8217;t copy it verbatim.</p>
<pre class="brush: as3; title: ; notranslate">
private function smoothStates():void
{
	const oneMinusRatio:Number = 1.0 - fixedTimestepAccumulatorRatio;

	//Makes it easier to wrap up the Box2D body in another object so we can track other variables.
	for each (var body:Body in bodies)
	{
		var box2Dbody = body.box2DBody;

		texture.position.x = fixedTimestepAccumulatorRatio * box2Dbody.GetPosition().x + (oneMinusRatio * body.previousPosition.x);

		texture.position.y = fixedTimestepAccumulatorRatio * box2Dbody.GetPosition().y + oneMinusRatio * body.previousPosition.y;

		texture.rotation = box2Dbody.GetAngle() * fixedTimestepAccumulatorRatio + oneMinusRatio * body.previousAngle;
	}
}

private function resetSmoothStates():void
{
	for each (var body:Body in bodies)
	{
		texture.position.x = body.previousPosition.x = body.box2Dbody.GetPosition().x;

		texture.position.y = body.previousPosition.y = body.box2Dbody.GetPosition().y;

		texture.rotation = body.previousAngle = body.box2Dbody.GetAngle();
	}
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.allanbishop.com/box-2d-2-1a-tutorial-part-10-fixed-time-step/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Box 2D 2.1a Tutorial – Part 9 (Platform camera)</title>
		<link>http://blog.allanbishop.com/box-2d-2-1a-tutorial-part-9-platform-camera/</link>
		<comments>http://blog.allanbishop.com/box-2d-2-1a-tutorial-part-9-platform-camera/#comments</comments>
		<pubDate>Tue, 12 Jul 2011 14:02:44 +0000</pubDate>
		<dc:creator>Allan Bishop</dc:creator>
				<category><![CDATA[Box2D]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://blog.allanbishop.com/?p=506</guid>
		<description><![CDATA[Continuing our Box2D camera tutorials, we will now look at creating a specific camera, that being the “Platform Camera”. The platform camera is similar to the follow camera, except that the camera will not always necessarily pan the world to keep the target in the centre of the screen. Instead, we will set invisible margins [...]]]></description>
			<content:encoded><![CDATA[<p><a class="lbpModal" title="Box2D platform camera demo" href="http://blog.allanbishop.com/wp-content/uploads/2011/07/Box2DCameraPlatformDemo.swf"><img src="http://blog.allanbishop.com/wp-content/uploads/2011/07/Box2DPlatformCamera.jpg" alt="" /></a></p>
<p>Continuing our Box2D camera tutorials, we will now look at creating a specific camera, that being the “Platform Camera”. The platform camera is similar to the follow camera, except that the camera will not always necessarily pan the world to keep the target in the centre of the screen. Instead, we will set invisible margins on the sides of the screen and only when the target crosses these boundaries will the camera pan to prevent the target from disappearing off the screen. <span id="more-506"></span></p>
<p>To start with, let’s create a new class called PlatformCamera and have it extend BasicCamera. In addition to the constructor’s parameters, we will pass in a margin value.</p>
<pre class="brush: as3; title: ; notranslate">
package Camera
{
	import flash.display.Sprite;

	public class PlatformCamera extends BasicCamera
	{
		private var _margin:Number;

		public function PlatformCamera(parent:Sprite,rasterWidth:Number,rasterHeight:Number,worldWidth:Number,worldHeight:Number,zoom:Number = 1,margin:Number = 120)
		{
			super(parent, rasterWidth, rasterHeight, worldWidth, worldHeight, zoom);
			_margin = 120;
		}
	}
}
</pre>
<p>Next, we will create a function called update that we will pass in the current raster position of the target we wish the camera to follow.</p>
<pre class="brush: as3; title: ; notranslate">
		public function update(rasterPosition:b2Vec2):void
		{

		}
</pre>
<p>After that, we need to test the position against the margins on all four sides to determine if the position has crossed any boundaries, and if so, by how much.<br />
Then, it is just a matter of calling our pan function to move the camera back by the amount that was overlapped to keep the position of the target at the edge of the boundary.</p>
<pre class="brush: as3; title: ; notranslate">
		public function update(rasterPosition:b2Vec2):void
		{
			var differenceX:Number = 0;
			var differenceY:Number = 0;

			if(rasterPosition.x &lt; _margin) 			{ 				differenceX = _margin - rasterPosition.x; 			} 			if(rasterPosition.x &gt; _rasterWidth - _margin)
			{
				differenceX = (_rasterWidth - _margin) - rasterPosition.x;
			}
			if(rasterPosition.y &lt; _margin) 			{ 				differenceY = _margin - rasterPosition.y; 			} 			if(rasterPosition.y &gt; _rasterHeight - _margin)
			{
				differenceY = (_rasterHeight - _margin) - rasterPosition.y;
			}

			pan(new b2Vec2((differenceX) / PIXELS_TO_METRE, (differenceY) / PIXELS_TO_METRE));
		}
</pre>
<p>Now that this is done, we need to create an instance of this camera and call the camera’s update function in the update function of the world update loop.</p>
<pre class="brush: as3; title: ; notranslate">
		//this is in the main CameraPlatformDemo Class
		protected function update(e:Event):void
		{
			var timeStep:Number = 1 / 60;
			var velocityIterations:int = 6;
			var positionIterations:int = 2;

			UpdateMouseWorld();
			MouseDestroy();
			MouseDrag();
			//apply the physics
			updatePhysics();
			//update the physics calculations
			_world.Step(timeStep, velocityIterations, positionIterations);
			//update the display based on the new physics
			var camera:PlatformCamera = ServiceLocator.resolve(PlatformCamera);
			var rasterPoint:b2Vec2 = camera.getRasterPoint(_trackBubble.body.GetPosition().x, _trackBubble.body.GetPosition().y);
			camera.update(new b2Vec2(rasterPoint.x,rasterPoint.y));
			updateTextures();
			var p:b2Vec2 = camera.getRasterPoint(_trackBubble.body.GetPosition().x, _trackBubble.body.GetPosition().y);
			_world.ClearForces();
			General.Input.update();
		}
//
		protected function init():void
		{
			ServiceLocator.register(new PlatformCamera(this, 800, 600, 1600/BasicCamera.PIXELS_TO_METRE,1200/BasicCamera.PIXELS_TO_METRE));

			_background = new Background();
			addChild(_background);
			_world = new b2World(new b2Vec2(0, 0), true);
			_ballContactListener = new BubbleContactListener();
			_world.SetContactListener(_ballContactListener);
			_input = new Input(stage);

			addEventListener(Event.ENTER_FRAME, update);
		}
</pre>
<p>There is one caveat, if the zoom value is set too high then the motion is not very smooth as the position of the target is not being set back exactly to the correct position. I suspect this is caused by floating point rounding errors. If anyone has time to fix it then that would be greatly appreciated.</p>
<p><a href="http://blog.allanbishop.com/wp-content/uploads/2011/07/Box2DPlatformCameraDemo.zip" target="_blank">Full source zip</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.allanbishop.com/box-2d-2-1a-tutorial-part-9-platform-camera/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Box 2D 2.1a Tutorial – Part 8 (Camera zooming)</title>
		<link>http://blog.allanbishop.com/box-2d-2-1a-tutorial-part-8-camera-zooming/</link>
		<comments>http://blog.allanbishop.com/box-2d-2-1a-tutorial-part-8-camera-zooming/#comments</comments>
		<pubDate>Sun, 13 Feb 2011 11:12:50 +0000</pubDate>
		<dc:creator>Allan Bishop</dc:creator>
				<category><![CDATA[Box2D]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://blog.allanbishop.com/?p=481</guid>
		<description><![CDATA[In the last tutorial we started work on our BasicCamera for Box2D, where we added functions such as lookAt and panning so we could translate our camera position, as well as helper functions to convert from world to raster coordinates and vice versa. We will again be revisiting this class. This time, so that we [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.allanbishop.com/wp-content/uploads/2011/02/CameraZoomDemo.swf" class="lbpModal" title="Box2D camera zooming demo"><img src="http://blog.allanbishop.com/wp-content/uploads/2011/02/CameraZoomTutorial.png" /> </a></p>
<p>In the last <a href="http://blog.allanbishop.com/box-2d-2-1a-tutorial-part-7-camera-panning/" target="_self">tutorial </a>we started work on our BasicCamera for Box2D, where we added functions such as lookAt and panning so we could translate our camera position, as well as helper functions to convert from world to raster coordinates and vice versa.</p>
<p>We will again be revisiting this class. This time, so that we can add zooming capabilities.<span id="more-481"></span></p>
<p>Adding the zooming is not too hard at all. Basically, wherever we have been using PIXELS_TO_METRE in the BasicCamera class, it is now necessary to multiply it by a zoom value.</p>
<p>So let&#8217;s open up the BasicCamera class from the last tutorial. You can grab the project files from <a href="http://blog.allanbishop.com/wp-content/uploads/2011/02/BasicCameraTutorialProjectComplete.zip">here</a>. </p>
<p>Start by adding a zoom parameter to our class’s constructor and create a class member variable that zoom will be assigned to. While we are at it, we will also create a class member variable called _adjustedPixelsToMeters which we will come back to later.</p>
<pre class="brush: as3; title: ; notranslate">
		private var _zoom:Number;
		private var _adjustedPixelsToMetre:Number;

		public function BasicCamera(parent:Sprite,rasterWidth:Number,rasterHeight:Number,worldWidth:Number,worldHeight:Number,zoom:Number=1)
		{
			_container = parent;
			_rasterWidth = rasterWidth;
			_rasterHeight = rasterHeight;
			_worldWidth = worldWidth;
			_worldHeight = worldHeight;
			this.zoom = zoom;
		}
</pre>
<p>Next, let&#8217;s create a getter and setter for the zoom.</p>
<pre class="brush: as3; title: ; notranslate">
		public function get zoom():Number
		{
			return _zoom;
		}

		public function set zoom(zoom:Number):void
		{
			_zoom = zoom;
		}
</pre>
<p>In the setter we want to scale the container by the zoom. One minor problem is that when we scale the container, the X and Y position stays the same but the width and height of the container changes. This means that as we zoom, the centre point of the world changes. To solve this, we can record the point in world coordinates that is currently in the center of the screen, apply the zoom, and then call our lookAt function to re-centre the display.</p>
<p>You might also notice that we have extensively used the PIXELS_TO_METRE constant throughout this class. Well, with zooming we need to multiply this value by the zoom value. So to make things tidier we are going to assign this value to the class member variable _adjustedPixelsToMetre that we created earlier.</p>
<pre class="brush: as3; title: ; notranslate">
		public function set zoom(zoom:Number):void
		{
			if(zoom&lt;=0)
				return;

			var wc:b2Vec2 = getWorldPoint(_rasterWidth / 2, _rasterHeight/2);

			_zoom = zoom;
			_container.scaleX = _zoom;
			_container.scaleY = _zoom;
			_adjustedPixelsToMetre = _zoom * PIXELS_TO_METRE;

			lookAt(new b2Vec2(wc.x, wc.y));
		}
</pre>
<p>Now that is done, we will change all the PIXELS_TO_METRE references in the BasicCamera class to the _adjustedPixelsToMetre. I will omit showing all the changes.</p>
<p>External classes such as the Bubble class, will still reference the PIXELS_TO_METRE as I find it handy to think in pixels when designing a world, but is not means necessary.</p>
<p>Finally, let&#8217;s update our onKeyPress function in the CameraDemo class so that we can test the zoom.</p>
<pre class="brush: as3; title: ; notranslate">
		private function onKeyPress(event:KeyboardEvent):void
		{
			var camera:BasicCamera = ServiceLocator.resolve(BasicCamera);

			switch(event.keyCode)
			{
				case Keyboard.LEFT:
					camera.pan(new b2Vec2(2, 0));
					break;
				case Keyboard.RIGHT:
					camera.pan(new b2Vec2(-2, 0));
					break;
				case Keyboard.UP:
					camera.pan(new b2Vec2(0, 2));
					break;
				case Keyboard.DOWN:
					camera.pan(new b2Vec2(0, -2));
					break;
				case Keyboard.C:
					camera.lookAt(new b2Vec2(800/BasicCamera.PIXELS_TO_METRE,600/BasicCamera.PIXELS_TO_METRE));
					break;
				//Plus key
				case 187:
					camera.zoom+=0.01;
					break;
				//Minus key
				case 189:
					camera.zoom-=0.01;
			}
		}
</pre>
<p>So there we are, another camera tutorial done. Once again <a href="http://blog.allanbishop.com/wp-content/uploads/2011/02/BasicCameraZoomTutorialCompleted.zip" target="_blank">here</a> is the completed project file for this tutorial. The next tutorial we will look at adding some logic to make our camera a bit smarter and more useful to us.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.allanbishop.com/box-2d-2-1a-tutorial-part-8-camera-zooming/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Box 2D 2.1a Tutorial – Part 7 (Camera panning)</title>
		<link>http://blog.allanbishop.com/box-2d-2-1a-tutorial-part-7-camera-panning/</link>
		<comments>http://blog.allanbishop.com/box-2d-2-1a-tutorial-part-7-camera-panning/#comments</comments>
		<pubDate>Wed, 02 Feb 2011 11:40:09 +0000</pubDate>
		<dc:creator>Allan Bishop</dc:creator>
				<category><![CDATA[Box2D]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://blog.allanbishop.com/?p=442</guid>
		<description><![CDATA[In the next chapter of the Box2D tutorial series, we will explore creating and utilizing a camera. Unlike the previous tutorials, these will be more focused on Flash, as the camera is, for the most part, separate to the Box2D engine. For this particular tutorial, we will be setting up a basic camera with the [...]]]></description>
			<content:encoded><![CDATA[<p><a class="lbpModal" title="Box 2D 2.1a Camera Panning" href="http://blog.allanbishop.com/wp-content/uploads/2011/02/CameraDemo.swf"><img src="http://blog.allanbishop.com/wp-content/uploads/2011/02/Box2DCameraTutorial.png" alt="" /> </a></p>
<p>In the next chapter of the Box2D tutorial series, we will explore creating and utilizing a camera. Unlike the previous tutorials, these will be more focused on Flash, as the camera is, for the most part, separate to the Box2D engine.</p>
<p>For this particular tutorial, we will be setting up a basic camera with the ability to pan and centre on any point in the Box2D world. <span id="more-442"></span></p>
<p>The most important concept is to remember that Box2D has a different coordinate system to the Flash’s raster display and so we will need to convert between the two when required. To make life easier we will be reusing one of the past demo’s, <a href="http://blog.allanbishop.com/box-2d-2-1a-tutorial-part-4-extended-contact-point/">CollisionPointDemo</a>, and implementing the camera with it. Grab the skeleton project <a href="http://blog.allanbishop.com/wp-content/uploads/2011/02/CameraBasicProjectSkeleton.zip">here</a>.</p>
<p>First up, let’s implement the skeleton camera class called <strong>BasicCamera</strong>.</p>
<p>The easiest way to deal with all the display objects will be to add them to a container display object. This way we can easily move and scale the container which will implicitly adjust all the child display objects. Therefore, we will pass in a reference to a container sprite into the BasicCamera class’ constructor together with stage’s width and height. You will also see that we have retained the PIXELS_TO_METRE const from the previous tutorials but just moved it into the skeleton class rather than having it in the <strong>constants </strong>class.</p>
<p>While we are at it, we should create a helper function, <strong>getCurrentOffset</strong>, as it will be required a lot. The reason we need this is that we will be panning the container sprite object to change what is currently on the screen. I think it will be best if the function returns the offset in world coordinates (Box2D coordinates). Therefore, we find the difference of the container from the origin (0,0) and then convert it into world coordinates. This can be done by dividing by the PIXELS_TO_METRE ratio.</p>
<pre class="brush: as3; title: ; notranslate">
		public function getCurrentOffset():b2Vec2
		{
			var x:Number = (0 - _container.x / (PIXELS_TO_METRE));
			var y:Number = (0 - _container.y / (PIXELS_TO_METRE));

			//guard against dividing by zero
			if(isNaN(x))
			{
				x = 0;
			}
			if(isNaN(y))
			{
				y = 0;
			}

			return new b2Vec2(x, y);
		}
</pre>
<p>I will also take some time to mention that Box2D’s coordinate system’s X and Y values increase to the east and north respectively, whilst Flash’s coordinate system’s X and Y values increase to the east and south respectively. This requires an extra step for finding any Y values.</p>
<p>You will notice that I have setup the instance of the BasicCamera class for you. As we need to use this class in lots of other classes, I will be using a design pattern known as the <a href="http://gameprogrammingpatterns.com/service-locator.html" target="_blank">ServiceLocator </a>to easily access the camera instance from anywhere. We should also address that the original CollisionPointDemo was in fact upside down, not that it made any difference, but for this tutorial it really should be the right way up. So in the Bubble class, in the update function, when we set the Y position of the texture we need to flip it.</p>
<pre class="brush: as3; title: ; notranslate">
		//Bubble class
		public function updateTexture():void
		{
			var camera:BasicCamera = ServiceLocator.resolve(BasicCamera);
			_texture.x = _body.GetPosition().x * BasicCamera.PIXELS_TO_METRE;
			_texture.y = camera.worldHeight*BasicCamera.PIXELS_TO_METRE - (_body.GetPosition().y * BasicCamera.PIXELS_TO_METRE);
			_texture.rotation = (_body.GetAngle() * Constants.RADIANS_TO_DEGREES) % 360;
		}
</pre>
<p>So back to the camera class, to begin, we will aim to centre the camera on a desired point in the world. We will call this the <strong>lookAt </strong>function.</p>
<p>This lookAt function will accept a b2Vector that will be the point in the Box2D’s world coordinate system for the camera to centre on.</p>
<p>Next we need to work out what is the current world coordinate in the centre of our raster display.</p>
<p>The X position is quite easy to work out as we just take half the raster width, convert it into world coordinates and add the offset. The Y position is a bit harder as Flash’s coordinate system has the Y value increasing downwards. So we need to flip it.</p>
<p>Now we find the difference between the current centre world point and the desired point to find out how much we need to pan the container by. Then we just need to convert this into the raster display coordinates so we can apply the values to the container’s X and Y.</p>
<pre class="brush: as3; title: ; notranslate">
		public function lookAt(at:b2Vec2):void
		{
			//get current offset
			var offset:b2Vec2 = getCurrentOffset();

			//get in world coordinates, what is the current point on the centre of
			//the raster display in wc m
			var currentX:Number = offset.x + (_rasterWidth / 2 / PIXELS_TO_METRE);
			//the 1200 is because we have to reverse the coordinate system of flash
			var currentY:Number = (_worldHeight ) - (offset.y + (_rasterHeight / 2 / PIXELS_TO_METRE));

			//calculate the change required to move the current world coordinates, to the desired
			//world coordinates
			var changeX:Number = at.x - currentX;
			var changeY:Number = at.y - currentY;

			//convert world coordinate updates to raster so we can move the sprite
			changeX = changeX * PIXELS_TO_METRE;
			changeY = changeY * PIXELS_TO_METRE;

			//apply changes
			_container.x -= changeX;
			_container.y += changeY;
		}
</pre>
<p>If you test this, it seems to work nicely, however, we have now have two problems. The first is when the bubbles collide, the smaller bubbles used to mark the impact no longer are in the correct position, and the second is that we can no longer click and drag a bubble.</p>
<p>So let’s deal with the first problem, and that is impact bubbles not being in the correct position. If you remember from the CollisionPoint tutorial, the manifold returned a vector of the collision in world coordinates, but it is the discrepancy between the Box2D point and the now offset raster sprite world causing the problem. Thus we need a function that we can pass in world coordinates and that will calculate what the point is in Flash’s raster display. This will be the purpose of the <strong>getRasterPoint </strong>function.</p>
<p>Finding the X position is easy, we just get the current X offset and find the difference between it and the world X coordinate that was passed in. Then we convert that back into Flash&#8217;s raster display. Finding the Y position is a little harder but the goal is the same. This time we want to find the Y offset as in the diagram below so will we will need to do a bit of math to work it out. For this part I find it easier to think in terms of Flash’s raster system so I will be converting any of the Box2D positions into it. Hopefully this diagram makes it a bit clearer.</p>
<p><img class="aligncenter size-full wp-image-448" title="CameraDemoDiagram" src="http://blog.allanbishop.com/wp-content/uploads/2011/02/CameraDemoDiagram.png" alt="Camera Demo Diagram" width="620" height="380" /></p>
<pre class="brush: as3; title: ; notranslate">
		public function getRasterPoint(worldX:Number,worldY:Number):b2Vec2
		{
			//convert world Y to raster y
			var worldYInRasterPixels:Number = worldY * PIXELS_TO_METRE;
			//convert world Y offset to raster
			var offsetYinRasterPixels:Number = getCurrentOffset().y * PIXELS_TO_METRE;
			//If we can line up the bottom of the world with the bottom of our flipped raster
			//then things become easier. First we want to find how much of the world is below our raster display
			var desiredYOffset:Number = (_worldHeight * PIXELS_TO_METRE) - offsetYinRasterPixels - _rasterHeight;
			//flip to suit Flash's coordinate system
			var flashRasterYPixels:Number = _rasterHeight - worldYInRasterPixels;

			var finalYPosition:Number = flashRasterYPixels + desiredYOffset;

			//going to work mainly in world cooridinates here
			var offsetXPixels:Number = getCurrentOffset().x ;
			var desiredXOffset:Number = worldX - offsetXPixels;
			var finalXPosition:Number = desiredXOffset * PIXELS_TO_METRE;

			return new b2Vec2(finalXPosition, finalYPosition);
		}
</pre>
<p>With this function complete, let’s go to the Bubble class to where we add the smaller bubbles in the addBubble function. Using our ServiceLocator, we can access an instance of the camera class. Let’s call the getRasterPoint function with the position of the collisions in world coordinates to retrieve the raster positions.</p>
<pre class="brush: as3; title: ; notranslate">
		//Bubble class
		public function addBubble(position:b2Vec2):void
		{

			var bubbleAnimation:SmallBubbleAnimation = new SmallBubbleAnimation();
			bubbleAnimation.alpha = 0.6;
			ColourUtilities.transformColour(bubbleAnimation.bubble.ball.mcBallBackground, _colour)

			var textureCoordinates:Point = new Point();

			var camera:BasicCamera = ServiceLocator.resolve(BasicCamera);

			textureCoordinates.x = 0;
			textureCoordinates.y = 0;

			var p:b2Vec2 = camera.getRasterPoint(position.x, position.y)
			textureCoordinates.x = p.x;
			textureCoordinates.y = p.y;

			texture.addChild(bubbleAnimation as MovieClip);

			var localPoint:Point = bubbleAnimation.globalToLocal(textureCoordinates);

			bubbleAnimation.x = localPoint.x;
			bubbleAnimation.y = localPoint.y;

			_bubbles.push(bubbleAnimation);

			if(_bubbles.length &gt; MAX_BUBBLES)
			{
				popBubble(_bubbles[0]);
				_bubbles.splice(0, 1);
			}
		}
</pre>
<p>If you test this, you should now see the small impact bubbles being added correctly.<br />
Now let’s fix the other problem, that being the mouse dragging not working.</p>
<p>If we look at the area of code that handles the mouse in the CameraDemo’s UpdateMouseWorld, you can see that we are just using remnants of the old camera system, where we convert Flash’s coordinates into the world coordinates. Of course, we are now panning which messes this up. So let’s fix it. What we require is a function that does the opposite of the function we just built, that being a function where we pass in a point in Flash’s raster coordinates which returns the point in world coordinates. We will call this function <strong>getWorldPoint</strong> and add it to the BasicCamera class.</p>
<pre class="brush: as3; title: ; notranslate">
		public function getWorldPoint(rasterX:Number,rasterY:Number):b2Vec2
		{
			//first, let's flip the Flash rastered coordinates so that y values increases as you move higher
			var flashRasterYPixels:Number = _rasterHeight - rasterY;
			//lets get the current offset and covert that offset into rastered pixels
			var offsetYinRasterPixels:Number = getCurrentOffset().y * PIXELS_TO_METRE;
			//If we can line up the bottom of the world with the bottom of our flipped raster
			//then things become easier. First we want to find how much of the world is below our raster display
			var desiredYOffsetAndRasterHeight:Number = (_worldHeight * PIXELS_TO_METRE) - offsetYinRasterPixels;
			var desiredYOffset:Number = desiredYOffsetAndRasterHeight - _rasterHeight;
			//add this offset to the flipped raster
			var finalYPosition:Number = flashRasterYPixels + desiredYOffset;
			//convert to metres
			finalYPosition /= (PIXELS_TO_METRE);

			//guard against dividing by zero
			if(isNaN(finalYPosition))
			{
				finalYPosition = 0;
			}

			var desiredXOffset:Number = getCurrentOffset().x * PIXELS_TO_METRE;
			var finalXPosition:Number = rasterX + desiredXOffset;
			finalXPosition /= BasicCamera.PIXELS_TO_METRE;

			//guard against dividing by zero
			if(isNaN(finalXPosition))
			{
				finalXPosition = 0;
			}

			return new b2Vec2(finalXPosition, finalYPosition);
		}
</pre>
<p>Once that is done, we then need to update the UpdateMouseWorld in the CameraDemo class.</p>
<pre class="brush: as3; title: ; notranslate">
		protected function UpdateMouseWorld():void
		{

			var cam:BasicCamera = ServiceLocator.resolve(BasicCamera);

			var b:b2Vec2 = cam.getWorldPoint(Input.mouseX, Input.mouseY);

			_mouseXWorldPhys = b.x;
			_mouseYWorldPhys = b.y;

			_mouseXWorld = (Input.mouseX);
			_mouseYWorld = (Input.mouseY);
		}
</pre>
<p>We should also add a pan function to the BasicCamera class. This is really simple to do.</p>
<pre class="brush: as3; title: ; notranslate">
		public function pan(amount:b2Vec2):void
		{
			_container.x += amount.x * PIXELS_TO_METRE;
			_container.y += amount.y * PIXELS_TO_METRE;
		}
</pre>
<p>For testing, we will use the arrow keys to pan the camera, and the C key to centre on the middle of the world. So we will code that in CameraDemo class too.</p>
<pre class="brush: as3; title: ; notranslate">
		private function onAddedToStage(e:Event):void
		{
			init();
			setup();
			stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPress);
		}

		private function onKeyPress(event:KeyboardEvent):void
		{
			var camera:BasicCamera = ServiceLocator.resolve(BasicCamera);

			switch(event.keyCode)
			{
				case Keyboard.LEFT:
					camera.pan(new b2Vec2(2, 0));
					break;
				case Keyboard.RIGHT:
					camera.pan(new b2Vec2(-2, 0));
					break;
				case Keyboard.UP:
					camera.pan(new b2Vec2(0, 2));
					break;
				case Keyboard.DOWN:
					camera.pan(new b2Vec2(0, -2));
					break;
				case Keyboard.C:
					camera.lookAt(new b2Vec2(800/BasicCamera.PIXELS_TO_METRE,600/BasicCamera.PIXELS_TO_METRE))
			}
		}
</pre>
<p>Give this a run and all should work as intended. I have included the completed project files <a href="http://blog.allanbishop.com/wp-content/uploads/2011/02/BasicCameraTutorialProjectComplete.zip">here</a>. In the next tutorial we will be adding zooming capabilities to the BasicCamera class.</p>
<p>FYI &#8211; the panning isn&#8217;t lagging. It only looks jittery as the movement only gets updated when a KeyboardEvent fires. For smoothing panning you will need to make use of the ENTER_FRAME event. I recommend using something like Bigroom&#8217;s KeyPoll class: http://code.google.com/p/bigroom/wiki/KeyPoll</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.allanbishop.com/box-2d-2-1a-tutorial-part-7-camera-panning/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Box2D AS3 port showdown</title>
		<link>http://blog.allanbishop.com/box2d-as3-port-showdown/</link>
		<comments>http://blog.allanbishop.com/box2d-as3-port-showdown/#comments</comments>
		<pubDate>Sun, 26 Dec 2010 02:50:18 +0000</pubDate>
		<dc:creator>Allan Bishop</dc:creator>
				<category><![CDATA[Benchmark]]></category>
		<category><![CDATA[Box2D]]></category>

		<guid isPermaLink="false">http://blog.allanbishop.com/?p=390</guid>
		<description><![CDATA[You might recall all the way back in my first Box2D tutorial, that I briefly mentioned there was two main ports of the Box2D engine for ActionScript 3.0, those being BorisTheBrave’s version and Jesse Sternberg’s alchemy version. For all these tutorials we have been using BorisTheBrave’s 2.1a, which leads me to discuss a recent video [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.allanbishop.combox2d-as3-ports-showdown"><img class="aligncenter size-full wp-image-401" title="Box2D AS3 port showdown" src="http://blog.allanbishop.com/wp-content/uploads/2010/12/Box2Dports.jpg" alt="" width="620" height="380" /></a><br />
You might recall all the way back in my first Box2D tutorial, that I briefly mentioned there was two main ports of the Box2D engine for ActionScript 3.0, those being BorisTheBrave’s version and Jesse Sternberg’s alchemy version.</p>
<p>For all these tutorials we have been using BorisTheBrave’s 2.1a, which leads me to discuss a recent video tutorial publish by the Adobe evangelist, Lee Brimelow. Lee’s excellent <a href="http://blog.theflashblog.com/?p=2465" target="_blank">tutorial </a>shows how to use the WCK framework to create Box2D worlds by laying out the various elements on the stage. This WCK framework makes use of the alchemy version of Box2D which led to a few readers to ask if the alchemy version of Box2D was faster than BorisTheBrave’s version.<span id="more-390"></span></p>
<p>Now I have never really tested the two versions before, and so was curious to find out myself, however, before we get to that, a little background information on the alchemy port.</p>
<p>The alchemy version of Box2D leverages Adobe’s Alchmey research project. Richard Szalay sums it up best as</p>
<p><em><strong>“Simply put, it&#8217;s an virtual machine that uses a ByteArray as it&#8217;s memory store. The C code compiled by Alchemy has direct access to &#8220;memory&#8221; (via some opcodes introduced in Flash 10), allowing it to chunk memory around at it&#8217;s leisure (including pointers to objects). This results in some, but by no means all, code running faster. Some types of code will actually run slower in Alchemy due to it being a VM running on top of the AVM (another VM). Additionally, Alchemy does not have native access to ActionScript classes and must access them through interop classes.”</strong></em> <em>- <a href="http://stackoverflow.com/questions/1869969/why-does-the-adobe-alchemy-tool-create-faster-running-flash-byte-code-than-the-fl" target="_blank">Richard Szalay</a></em></p>
<p>So while alchemy can provide a speed increase, it is by no means a silver bullet for performance.</p>
<p>My first test was to modify one of my earlier tutorials by increasing the ball count to 400 and test both Box2D ports on a Windows XP machine at work. Early results suggested they were both on par for performance, but surprisingly BorisTheBrave’s version used half as much ram.</p>
<p>These results surprised me, so I decided to recreate a new test from scratch, running on my home machine which is using Windows 7 64bit. BorisTheBrave’s version averaged about <strong>14 FPS</strong> and used on average <strong>17MB</strong> of ram. The Alchemy port averaged about <strong>19 FPS</strong> and used on average <strong>13MB </strong>of ram. Apart from outpeforming BorisTheBrave&#8217;s port, it was also much more consistent with memory usage. As it is currently the holidays I have been unable to reexamine my original test, but I feel these latest tests are more accurate. So please, feel free to post your results.</p>
<p style="text-align: center;"><a class="lbpModal" title="Alchemy Box2D port test" href="http://blog.allanbishop.com/wp-content/uploads/2010/12/AlchemyTest.swf"><img src="http://blog.allanbishop.com/wp-content/uploads/2010/12/Alchemy.jpg" alt="" /></a></p>
<p style="text-align: center;"><a href="http://blog.allanbishop.com/wp-content/uploads/2010/12/AlchemyTest.zip" target="_blank">source files</a></p>
<p style="text-align: center;"><a class="lbpModal" title="BorisTheBrave Box2D port test" href="http://blog.allanbishop.com/wp-content/uploads/2010/12/BorisTheBraveTest.swf"><img src="http://blog.allanbishop.com/wp-content/uploads/2010/12/Boris.jpg" alt="" /></a></p>
<p style="text-align: center;"><a href="http://blog.allanbishop.com/wp-content/uploads/2010/12/BorisTheBraveTest.zip" target="_blank">source files</a></p>
<p>I should point out that you cannot simply plug in the Alchemy port of Box2D when you have written code for BorisTheBrave’s port and vice versa. That being said, it is not every hard to tweak it. The biggest change I found was regarding the usage of Vectors.</p>
<p>With BorisTheBrave’s version we always use a <strong>b2Vec2</strong> class. With Alchemy we sometimes use the b2Vec2 and sometimes use another new class called<strong> V2</strong>. V2 is what you create instances of, you never create instances of b2Vec2 anymore. This is because it now only accepts one parameter which acts like a pointer. However, there are still classes that use the b2Vec2 so simply just change the x and y properties and don’t assign a new instance to it.</p>
<p>Apart from that, the other changes are typically properties that were actually functions that are now real properties. For example, b2ChircleShape, the radius is set by setting the <strong>m_radius</strong> property. Feel free to browse my code to see the changes. If you have any comments, just post them below.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.allanbishop.com/box2d-as3-port-showdown/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Box 2D 2.1a Tutorial – Part 6 (Collision strength)</title>
		<link>http://blog.allanbishop.com/box-2d-2-1a-tutorial-part-6-collision-strength/</link>
		<comments>http://blog.allanbishop.com/box-2d-2-1a-tutorial-part-6-collision-strength/#comments</comments>
		<pubDate>Thu, 16 Dec 2010 11:41:16 +0000</pubDate>
		<dc:creator>Allan Bishop</dc:creator>
				<category><![CDATA[Box2D]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://blog.allanbishop.com/?p=361</guid>
		<description><![CDATA[Today, we will once again be returning to the topic of collisions to answer a request which was, &#8220;how to determine the strength involved in a collision&#8221;. By gaining access to this information, we can then decide when to implement sound effects, damage modeling, score, etc. Currently, we have been using the b2ContactListener for detection [...]]]></description>
			<content:encoded><![CDATA[<p><a class="lbpModal" title="Box2D Asteroids" href="http://blog.allanbishop.com/wp-content/uploads/2010/12/AsteroidsDemo.swf"><img src="http://blog.allanbishop.com/wp-content/uploads/2010/12/Asteroids.jpg" alt="" /> </a></p>
<p>Today, we will once again be returning to the topic of collisions to answer a request which was,<em> &#8220;how to determine the strength involved in a collision&#8221;</em>. By gaining access to this information, we can then decide when to implement sound effects, damage modeling, score, etc.<span id="more-361"></span></p>
<p>Currently, we have been using the b2ContactListener for detection of when a collision occurs by overwriting the BeginContact function and accessing the b2Contact parameter. However, you will notice that the b2Contact does not offers us anything for determining the forces involved in a collision.</p>
<p>The secret is that we need to make use of another function of the b2ContactListener, the PostResolve function, which is called after collision detection and resolution has occurred. By overwriting this, not only do we get access to a b2Contact parameter, but we can also gain access to a b2ContactImpulse parameter.<br />
The b2ContactImpulse has two fields of interest. The normalImpulses and tangentImpulses, both of type Vector. A quick look in the Box2D manual reveals their purpose:</p>
<ul>
<li><strong>normal impulse<br />
</strong>The normal force is the force applied at a contact point to prevent the shapes from penetrating. For convenience, Box2D works with impulses. The normal impulse is just the normal force multiplied by the time step.</li>
<li><strong>tangent impulse</strong><br />
The tangent force is generated at a contact point to simulate friction. For convenience, this is stored as an impulse.</li>
</ul>
<p>So it would seem normal impulse is what we are after. My understanding is the force to prevent shapes overlapping is going to be equal to the force causing it to overlap in the first place.</p>
<p>Thus for each contact, we will receive a Vector of normalImpulses. However, from my tests, it seems only the first value is of any use, with the second value seemingly to always be 0 (in saying so, there is probably a case where this won’t be true). We can then use this value to determine the magnitude of the force and use this however we please. In my asteroids demo, I simply check to see if this value is above a threshold, and if it is, I mark it for exploding.</p>
<pre class="brush: as3; title: ; notranslate">
package
{
	import Box2D.Dynamics.Contacts.b2Contact;
	import Box2D.Dynamics.b2ContactImpulse;
	import Box2D.Dynamics.b2ContactListener;

	public class AsteroidContactListener extends b2ContactListener
	{
		override public function PostSolve(contact:b2Contact, impulse:b2ContactImpulse):void
		{
			if(impulse.normalImpulses[0] &gt; 70)
			{
				if(contact.GetFixtureA() != null)
				{
					var asteroidOne:Asteroid = contact.GetFixtureA().GetBody().GetUserData();
					asteroidOne.collide = true;
				}
				if(contact.GetFixtureB() != null)
				{
					var asteroidTwo:Asteroid = contact.GetFixtureB().GetBody().GetUserData();
					asteroidTwo.collide = true;
				}
			}
		}
	}
}
</pre>
<p><a title="Full zipped source (with limited artwork)" href="http://blog.allanbishop.com/wp-content/uploads/2010/12/AsteroidCollisionLimitedArtwork.zip">Full zipped source (with limited artwork)</a></pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.allanbishop.com/box-2d-2-1a-tutorial-part-6-collision-strength/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
	</channel>
</rss>

