Starling, Nape Physics, and PhysicsEditor

While there are seemingly countless tutorials, articles, and assorted commentaries on using TexturePacker with Flash (and usually Starling), it seems there are very few articles out there about TexturePacker’s creator’s (Andreas Löw) other equally fantastic tool PhysicsEditor. Since I’m currently working on a game that makes extensive use of this software, I thought I’d take a bit of time off to write a little about it.

If you don’t know what it is, in a nutshell, PhysicsEditor allows you to import .png files, trace their shapes, then export matching physics bodies for the framework of your choice (assuming your choice is AndEngine, Box2D, CitrusEngine, Corona, Chipmunk, Gideros, Lime + Corona, Nape, QuickBox2D, or RapaNui – and, really, what else is there?) in code form. I’ll give a quick run through on exporting some bodies for the Nape AS3 engine, so if you want to be able to compile the end result, you’ll need the latest Nape release, PhsyicsEditor, of course (there’s a free trial available), and Starling.

First you’ll need some images to play around with. Just for complexity, for this demo, I chose a gear and a wacky ground I just drew up at random. You’re welcome to play around with these, but for the sake of full disclosure, I found the gear in a Google image search, so I wouldn’t go using it for anything other than testing.

One of the great things about PhysicsEditor is that you can simply load in the actual textures you plan on using in your game or app so unless you wind up resizing your assets later, you’ll get a perfect WYSIWYG result.

So, fire up PE and load in your images using the ‘Add Sprites’ button on the top tool bar. Once imported, to the left you’ll see a list of the currently added images. If you used your own images and didn’t give them meaningful names (e.g. you named them ’01.png’ or some such thing), now would be a good time to  do so. Double click the name of the image and change it to something more meaningful like ‘ground’, or ‘gear’ or whatever (you’ll see why you’ll want to do so in a bit). Now on your images (one at a time), click the ‘shape tracer’ button (the little magic wand icon just above the big image in the center). This will open a new window called ‘Tracer’ and automatically trace a shape around your image. Of course you’re welcome to play around with the settings here, but I find the defaults to work just fine. More than likely the shape won’t be perfect, but we’ll fix that in just a second.

After clicking ‘OK’ in the Tracer window, you’ll be taken back to the Main window, but now see a reddish shape around your image. For a closer look, you can use the slider beneath the image window to zoom in and out. As mentioned, your traced shape probably won’t be perfect, but at this point, you can click on vertex points to move them around. And by right clicking, you can delete any unnecessary vertex points or add new ones anywhere on the path. The goal is to trace a path as perfectly as possible around your image while keeping the vertex count as low as possible. After about 30 seconds of mucking about, my gear image wound up looking like this.

My ground image took even less fixing up.

Next you’ll want to choose an exporter. From the drop down menu to the left select ‘Nape (AS3)’. You’ll see some more settings you can play around with, but the only thing I changed in this demo was the anchor point which I placed right in the center for both ground and gear. You can do this quickly and easily by changing the relative x and y coordinates to both be .5. Like the Flash display list, this is the registration point of your physics body and will affect how they’re positioned when we get to that point.

At this time, you’re ready to go. However, if you were to publish right now, you would wind up with several errors in your code. This is because the Nape Physics API has been updated since the last release PhysicsEditor (I’m sure it’s hard keeping up to date when supporting all those freaking engines). Thankfully, Andreas Löw has made it incredibly easy to keep the exporters up to date ourselves. Go to the installation directory of PhysicsEditor and find the ‘exporters’ directory. Browse into that then go down and move into the ‘nape-as3′ directory. Inside there, you’ll see a ‘nape.as’ file. Open that in a text or code editor and every place you see ‘cbType =’, change it to ‘cbTypes.add()’. So, for example:

body.cbType = cbtype("{{body.cbType}}");

will become:

body.cbTypes.add(cbtype("{{body.cbType}}"));

and:

s.cbType = cbType;

will become:

s.cbTypes.add(cbType);

etc.

If you’re not familiar with Nape, CBTypes are short for Call Back Types. You can create your own call back types and apply them to physics bodies so that interactions will have different results. For example, a collision between two gears may play a different sound than a collision between a gear and the ground. In previous versions of Nape each body could only have a single call back type applied. Now, however, call back types are added to a list and you can have several on a single body. For this basic demo we won’t bother with any cbTypes, but, again, without making these changes to the export, your final project will be filled with errors.

NOTE: by the time you read this, this discrepancy may be fixed and none of this may be necessary. I’m currently using the 1.0.9 version of PhysicsEditor.

So, once the exporter file has been fixed (you only have to do this one time), you’re ready to publish your actionscript file. Click on the ‘Publish’ or ‘Publish As’ button on the top tool bar and save the file to your project root (or anywhere you’ll remember if you haven’t created a project yet) with the default name ‘PhysicsData.as’.

ANOTHER NOTE: if you choose a different file name or publish to a package other than the root of your project, you’ll have to edit the .as file to reflect these changes. No big deal.

Now, you’re ready to start writing some code. If you haven’t already done so, create a new Actionscript project somewhere. I set mine to export a 800×600 .swf file with a framerate of 60. I also embedded the ground and gear images (same ones I used in PhysicsEditor). Of course you could create an image Atlas (with something like TexturePacker, for example), but for only two textures, I really didn’t want to go through the trouble.

The first thing you’ll want to do is initialize Starling. In my example, I have a very basic mStarlingBase instance which inherits from the Starling Sprite class and does really nothing but act as container to which I can add some Starling images.

After Starling is good to go, we’ll initialize the Nape Physics engine. Unlike other physics engines, Nape is extremely easy to set up. Really all you need to do is create an instance of the Space class and pass it a Vec2 instance which defines gravity and you’re good to go. For this example though, I also create a PivotJoint instance which will be used to add mouse interactivity so you drag and throw the gears around. So my initPhysics method looks like this:

mSpace = new Space(new Vec2(0, 1000));
 
mHand = new PivotJoint(mSpace.world, null, new Vec2(), new Vec2());
mHand.active = false;
mHand.stiff = false;
mHand.space = mSpace;

(1000 may seem like a high gravity, but Nape just seems to look and perform better with very high gravity set. Adjust to your own taste).

Once the physics space is ready, we can start adding physics bodies. First we’ll initialize the ground. The first thing we’ll do is create a Starling image from the embedded ground image bitmap data and add it to the Starling base. After that, we create a Nape physics body using a static method of the PhysicsData class exported from PhysicsEditor – var ground:Body = PhysicsData.createBody(“ground”); And now you can see why it was important to give your images meaningful names back in PE – writing PhysicsData.createBody(“01″) just wouldn’t be the same. Notice that this static method can also take a graphic argument. We’re not going to bother with that though. More on that in just a bit. Since our ground will never move, we set its ‘type’ property to static. We then position it in the center of the screen (recall back in PE we set the registration point to be in the center – this is where it makes a difference). Finally we add the body to the physics simulation just by setting its space property to our mSpace instance. The entire initGround() method looks like this:

var groundTexture:Texture = Texture.fromBitmapData(new GROUND_IMG().bitmapData, false);
var groundImage:Image = new Image(groundTexture);
groundImage.touchable = false;
mStarlingBase.addChild(groundImage);
 
var ground:Body = PhysicsData.createBody("ground");
ground.type = BodyType.STATIC;
ground.position.setxy(stage.stageWidth >> 1, stage.stageHeight >> 1);
ground.space = mSpace;

Next, we’ll add some gears into the mix. Since I want to add 3, I’ll do it in a simple for loop. This is done essentially the same as we added the ground with one slight difference. Since these gears will be moving around, we’ll want to associate our gear image with the gear physics body. In many Nape tutorials, you’ll see people telling you to use the ‘graphic’ property of the body instance. That property is being deprecated though and it is now recommended that you add your graphics to the ‘userData’ property of the body; which is just a generic object that any data can be added to. Also note that when we create our gear images, we adjust the pivot point to match the centered anchor point of the gear body. So, the initGears() method looks like:

var gearTexture:Texture = Texture.fromBitmapData(new GEAR_IMG().bitmapData, false);
 
for (var i:int = 0; i < 3; i++)
{
	var gearImage:Image = new Image(gearTexture);
	gearImage.touchable = false;
	gearImage.pivotX += gearImage.width >> 1;
	gearImage.pivotY += gearImage.height >> 1;
	mStarlingBase.addChild(gearImage);
 
	var gear:Body = PhysicsData.createBody("gear");
	gear.position.setxy(Math.random() * stage.stageWidth, Math.random() * -500);
	gear.userData.graphic = gearImage;
	gear.space = mSpace;
}

Now that our physics bodies are in place, we add some MouseEvent listeners to handle our mouse interaction and, finally, an EnterFrame listener to update our physics simulation. To update the Nape Physics engine, it’s really only necessary to call the step() method of the Space instance. In our case though, we also want to update our PivotJoint for mouse interactions, and, more importantly we want to update the images associated with the gear bodies. So our enter frame handler looks like this:

mHand.anchor1.setxy(mouseX, mouseY);
mSpace.step(1 / 60);
mSpace.liveBodies.foreach(updateGraphics);

Notice that to update our graphics we loop through the live bodies in our Space instance and for each of them call a method called updateGraphics. This method expects a Body instance as an argument and looks like:

private function updateGraphics(body:Body):void
{
	// if the body goes off screen and falls too far move it back up.
	if (body.position.y > 600)
	{
		body.position.setxy(Math.random() * stage.stageWidth, -200);
	}
 
	var image:Image = body.userData.graphic as Image;
	image.x = body.position.x;
	image.y = body.position.y;
	image.rotation = body.rotation;
}

And that is really the entire gist of it. Assuming all goes well, you should wind up with something like this. As you can see, even with such complex physics shapes as gears and that crazy ground, you still get an app that runs at a framerate of 60 FPS.

But, of course, the main point was just how easy it is to create complex physics shapes using Andreas Löw’s fantastic PhysicsEditor tool.

The entire code is listed below:

The document class, Main.as:

/**
 *	Copyright (c) 2012 Devon O. Wolfgang
 *
 *	Permission is hereby granted, free of charge, to any person obtaining a copy
 *	of this software and associated documentation files (the "Software"), to deal
 *	in the Software without restriction, including without limitation the rights
 *	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *	copies of the Software, and to permit persons to whom the Software is
 *	furnished to do so, subject to the following conditions:
 *
 *	The above copyright notice and this permission notice shall be included in
 *	all copies or substantial portions of the Software.
 *
 *	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *	THE SOFTWARE.
 */
 
package 
{
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import nape.constraint.PivotJoint;
	import nape.geom.Vec2;
	import nape.phys.Body;
	import nape.phys.BodyList;
	import nape.phys.BodyType;
	import nape.space.Space;
	import starling.core.Starling;
	import starling.display.Image;
	import starling.textures.Texture;
 
 
	[SWF(width='800', height='600', backgroundColor='#CCCCCC', frameRate='60')]
	public class Main extends flash.display.Sprite 
	{
 
		[Embed(source = "../assets/ground.png")]
		public static const GROUND_IMG:Class;
 
		[Embed(source = "../assets/gear.png")]
		public static const GEAR_IMG:Class;
 
 
		private var mStarlingBase:StarlingBase;
		private var mSpace:Space;
		private var mHand:PivotJoint;
 
		public function Main():void 
		{
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}
 
		private function init(event:Event = null):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
 
			stage.scaleMode = StageScaleMode.NO_SCALE;
			stage.align = StageAlign.TOP_LEFT;
 
			initStarling();
		}
 
		private function initStarling():void
		{
			var s:Starling = new Starling(StarlingBase, stage);
			s.addEventListener("rootCreated", onStarlingRoot);
			s.start();
		}
 
		private function onStarlingRoot(event:*):void
		{
			var s:Starling = event.currentTarget as Starling;
			s.removeEventListener("rootCreated", onStarlingRoot);
			Starling.current.showStats = true;
			Starling.current.stage.color = 0xCCCCCC;
			mStarlingBase = s.root as StarlingBase;
 
			initPhysics();
			initGround();
			initGears();
 
			stage.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
			stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
			addEventListener(Event.ENTER_FRAME, onFrame);
		}
 
		private function onMouseDown(event:MouseEvent):void
		{
			var mousePos:Vec2 = new Vec2(mouseX, mouseY);
			var bodies:BodyList = mSpace.bodiesUnderPoint(mousePos);
			for (var i:int = 0; i < bodies.length; i++) 
			{
				var b:Body = bodies.at(i);
				if(!b.isDynamic()) continue;
				mHand.body2 = b;
				mHand.anchor2 = b.worldToLocal(mousePos);
				mHand.active = true;
				break;
			}
		}
 
		private function onMouseUp(event:MouseEvent):void
		{
			mHand.active = false;
		}
 
		private function initPhysics():void
		{
			mSpace = new Space(new Vec2(0, 1000));
 
			mHand = new PivotJoint(mSpace.world, null, new Vec2(), new Vec2());
			mHand.active = false;
			mHand.stiff = false;
			mHand.space = mSpace;
		}
 
		private function initGround():void
		{
			var groundTexture:Texture = Texture.fromBitmapData(new GROUND_IMG().bitmapData, false);
			var groundImage:Image = new Image(groundTexture);
			groundImage.touchable = false;
			mStarlingBase.addChild(groundImage);
 
			var ground:Body = PhysicsData.createBody("ground");
			ground.type = BodyType.STATIC;
			ground.position.setxy(stage.stageWidth >> 1, stage.stageHeight >> 1);
			ground.space = mSpace;
		}
 
		private function initGears():void
		{
			var gearTexture:Texture = Texture.fromBitmapData(new GEAR_IMG().bitmapData, false);
 
			for (var i:int = 0; i < 3; i++)
			{
				var gearImage:Image = new Image(gearTexture);
				gearImage.touchable = false;
				gearImage.pivotX += gearImage.width >> 1;
				gearImage.pivotY += gearImage.height >> 1;
				mStarlingBase.addChild(gearImage);
 
				var gear:Body = PhysicsData.createBody("gear");
				gear.position.setxy(Math.random() * stage.stageWidth, Math.random() * -500);
				gear.userData.graphic = gearImage;
				gear.space = mSpace;
			}
		}
 
		private function onFrame(event:Event):void
		{
			mHand.anchor1.setxy(mouseX, mouseY);
			mSpace.step(1 / 60);
			mSpace.liveBodies.foreach(updateGraphics);
		}
 
		private function updateGraphics(body:Body):void
		{
			// if the body goes off screen and falls too far move it back up.
			if (body.position.y > 600)
			{
				body.position.setxy(Math.random() * stage.stageWidth, -200);
			}
 
			var image:Image = body.userData.graphic as Image;
			image.x = body.position.x;
			image.y = body.position.y;
			image.rotation = body.rotation;
		}
	}
 
}
 
 
 
 
class StarlingBase extends starling.display.Sprite
{
 
	public function StarlingBase() 
	{}
 
}

And the PhysicsData.as class exported from PhysicsEditor:

/**
 *	Copyright (c) 2012 Devon O. Wolfgang
 *
 *	Permission is hereby granted, free of charge, to any person obtaining a copy
 *	of this software and associated documentation files (the "Software"), to deal
 *	in the Software without restriction, including without limitation the rights
 *	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *	copies of the Software, and to permit persons to whom the Software is
 *	furnished to do so, subject to the following conditions:
 *
 *	The above copyright notice and this permission notice shall be included in
 *	all copies or substantial portions of the Software.
 *
 *	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *	THE SOFTWARE.
 */
 
 
 
package {
 
import nape.phys.Body;
import nape.phys.BodyType;
import nape.shape.Shape;
import nape.shape.Polygon;
import nape.shape.Circle;
import nape.geom.Vec2;
import nape.dynamics.InteractionFilter;
import nape.phys.Material;
import nape.phys.FluidProperties;
import nape.callbacks.CbType;
import nape.geom.AABB;
 
import flash.display.DisplayObject;
import flash.geom.Rectangle;
import flash.utils.Dictionary;
 
public class PhysicsData {
 
	public static function createBody(name:String,graphic:DisplayObject=null):Body {
		var xret:BodyPair = lookup(name);
		if(graphic==null) return xret.body.copy();
 
		var ret:Body = xret.body.copy();
		graphic.x = graphic.y = 0;
		graphic.rotation = 0;
		var bounds:Rectangle = graphic.getBounds(graphic);
		var offset:Vec2 = Vec2.get(bounds.x-xret.anchor.x, bounds.y-xret.anchor.y);
 
		ret.graphic = graphic;
		ret.graphicUpdate = function(b:Body):void {
			var gp:Vec2 = b.localToWorld(offset);
			graphic.x = gp.x;
			graphic.y = gp.y;
			graphic.rotation = (b.rotation*180/Math.PI)%360;
		}	
 
		return ret;
	}
 
	public static function registerMaterial(name:String,material:Material):void {
		if(materials==null) materials = new Dictionary();
		materials[name] = material;	
	}
	public static function registerFilter(name:String,filter:InteractionFilter):void {
		if(filters==null) filters = new Dictionary();
		filters[name] = filter;
	}
	public static function registerFluidProperties(name:String,properties:FluidProperties):void {
		if(fprops==null) fprops = new Dictionary();
		fprops[name] = properties;
	}
	public static function registerCbType(name:String,cbType:CbType):void {
		if(types==null) types = new Dictionary();
		types[name] = cbType;
	}
 
	//----------------------------------------------------------------------	
 
	private static var bodies   :Dictionary;
	private static var materials:Dictionary;
	private static var filters  :Dictionary;
	private static var fprops   :Dictionary;
	private static var types    :Dictionary;
	private static function material(name:String):Material {
		if(name=="default") return new Material();
		else {
			if(materials==null || materials[name] === undefined)
				throw "Error: Material with name '"+name+"' has not been registered";
			return materials[name] as Material;
		}
	}
	private static function filter(name:String):InteractionFilter {
		if(name=="default") return new InteractionFilter();
		else {
			if(filters==null || filters[name] === undefined)
				throw "Error: InteractionFilter with name '"+name+"' has not been registered";
			return filters[name] as InteractionFilter;
		}
	}
	private static function fprop(name:String):FluidProperties {
		if(name=="default") return new FluidProperties();
		else {
			if(fprops==null || fprops[name] === undefined)
				throw "Error: FluidProperties with name '"+name+"' has not been registered";
			return fprops[name] as FluidProperties;
		}
	}
	private static function cbtype(name:String):CbType {
		if(name=="null") return CbType.ANY_BODY;
		else {
			if(types==null || types[name] === undefined)
				throw "Error: CbType with name '"+name+"' has not been registered";
			return types[name] as CbType;
		}	
	}
 
	private static function lookup(name:String):BodyPair {
		if(bodies==null) init();
		if(bodies[name] === undefined) throw "Error: Body with name '"+name+"' does not exist";
		return bodies[name] as BodyPair;
	}
 
	//----------------------------------------------------------------------	
 
	private static function init():void {
		bodies = new Dictionary();
 
		var body:Body;
		var mat:Material;
		var filt:InteractionFilter;
		var prop:FluidProperties;
		var cbType:CbType;
		var s:Shape;
		var anchor:Vec2;
 
 
			body = new Body();
			body.cbTypes.add(cbtype("null"));
 
 
				mat = material("default");
				filt = filter("default");
				prop = fprop("default");
				cbType = cbtype("null");
 
 
 
						s = new Polygon(
							[   Vec2.weak(117,29.5)   ,  Vec2.weak(95,31)   ,  Vec2.weak(105,57)   ,  Vec2.weak(120.5,45)   ],
							mat,
							filt
						);
						s.body = body;
						s.fluidEnabled = false;
						s.fluidProperties = prop;
						s.cbTypes.add(cbType);
 
						s = new Polygon(
							[   Vec2.weak(3,29.5)   ,  Vec2.weak(-1,44)   ,  Vec2.weak(15,56)   ,  Vec2.weak(24,32)   ],
							mat,
							filt
						);
						s.body = body;
						s.fluidEnabled = false;
						s.fluidProperties = prop;
						s.cbTypes.add(cbType);
 
						s = new Polygon(
							[   Vec2.weak(28.5,117)   ,  Vec2.weak(43,123)   ,  Vec2.weak(56,106)   ,  Vec2.weak(31,97)   ],
							mat,
							filt
						);
						s.body = body;
						s.fluidEnabled = false;
						s.fluidProperties = prop;
						s.cbTypes.add(cbType);
 
						s = new Polygon(
							[   Vec2.weak(28,4)   ,  Vec2.weak(31,26)   ,  Vec2.weak(57,16)   ,  Vec2.weak(43,-1)   ],
							mat,
							filt
						);
						s.body = body;
						s.fluidEnabled = false;
						s.fluidProperties = prop;
						s.cbTypes.add(cbType);
 
						s = new Polygon(
							[   Vec2.weak(92,5)   ,  Vec2.weak(77,-1)   ,  Vec2.weak(64,16)   ,  Vec2.weak(90,26)   ],
							mat,
							filt
						);
						s.body = body;
						s.fluidEnabled = false;
						s.fluidProperties = prop;
						s.cbTypes.add(cbType);
 
						s = new Polygon(
							[   Vec2.weak(3,92)   ,  Vec2.weak(24,90)   ,  Vec2.weak(15,66)   ,  Vec2.weak(-2,78)   ],
							mat,
							filt
						);
						s.body = body;
						s.fluidEnabled = false;
						s.fluidProperties = prop;
						s.cbTypes.add(cbType);
 
						s = new Polygon(
							[   Vec2.weak(91,118)   ,  Vec2.weak(89,96)   ,  Vec2.weak(64,106)   ,  Vec2.weak(77,122)   ],
							mat,
							filt
						);
						s.body = body;
						s.fluidEnabled = false;
						s.fluidProperties = prop;
						s.cbTypes.add(cbType);
 
						s = new Polygon(
							[   Vec2.weak(122,79)   ,  Vec2.weak(106,66)   ,  Vec2.weak(95,90.5)   ,  Vec2.weak(117,92)   ],
							mat,
							filt
						);
						s.body = body;
						s.fluidEnabled = false;
						s.fluidProperties = prop;
						s.cbTypes.add(cbType);
 
						s = new Polygon(
							[   Vec2.weak(106,66)   ,  Vec2.weak(105,57)   ,  Vec2.weak(95,31)   ,  Vec2.weak(64,16)   ,  Vec2.weak(57,16)   ,  Vec2.weak(64,106)   ,  Vec2.weak(89,96)   ,  Vec2.weak(95,90.5)   ],
							mat,
							filt
						);
						s.body = body;
						s.fluidEnabled = false;
						s.fluidProperties = prop;
						s.cbTypes.add(cbType);
 
						s = new Polygon(
							[   Vec2.weak(24,32)   ,  Vec2.weak(15,56)   ,  Vec2.weak(15,66)   ,  Vec2.weak(24,90)   ,  Vec2.weak(56,106)   ,  Vec2.weak(64,106)   ,  Vec2.weak(57,16)   ,  Vec2.weak(31,26)   ],
							mat,
							filt
						);
						s.body = body;
						s.fluidEnabled = false;
						s.fluidProperties = prop;
						s.cbTypes.add(cbType);
 
						s = new Polygon(
							[   Vec2.weak(31,97)   ,  Vec2.weak(56,106)   ,  Vec2.weak(24,90)   ],
							mat,
							filt
						);
						s.body = body;
						s.fluidEnabled = false;
						s.fluidProperties = prop;
						s.cbTypes.add(cbType);
 
						s = new Polygon(
							[   Vec2.weak(90,26)   ,  Vec2.weak(64,16)   ,  Vec2.weak(95,31)   ],
							mat,
							filt
						);
						s.body = body;
						s.fluidEnabled = false;
						s.fluidProperties = prop;
						s.cbTypes.add(cbType);
 
 
 
 
			anchor =  Vec2.get(61,61);
			body.translateShapes(Vec2.weak(-anchor.x,-anchor.y));
			body.position.setxy(0,0);
 
			bodies["gear"] = new BodyPair(body,anchor);
 
			body = new Body();
			body.cbTypes.add(cbtype("null"));
 
 
				mat = material("default");
				filt = filter("default");
				prop = fprop("default");
				cbType = cbtype("null");
 
 
 
						s = new Polygon(
							[   Vec2.weak(20,-0.5)   ,  Vec2.weak(1,-0.5)   ,  Vec2.weak(10.5,58)   ],
							mat,
							filt
						);
						s.body = body;
						s.fluidEnabled = false;
						s.fluidProperties = prop;
						s.cbTypes.add(cbType);
 
						s = new Polygon(
							[   Vec2.weak(543.5,364)   ,  Vec2.weak(544.5,380)   ,  Vec2.weak(559.5,430)   ,  Vec2.weak(729,242)   ,  Vec2.weak(675,245.5)   ,  Vec2.weak(654.5,254)   ,  Vec2.weak(577.5,324)   ,  Vec2.weak(550.5,351)   ],
							mat,
							filt
						);
						s.body = body;
						s.fluidEnabled = false;
						s.fluidProperties = prop;
						s.cbTypes.add(cbType);
 
						s = new Polygon(
							[   Vec2.weak(774.5,0)   ,  Vec2.weak(764.5,90)   ,  Vec2.weak(799.5,598)   ,  Vec2.weak(799,-0.5)   ],
							mat,
							filt
						);
						s.body = body;
						s.fluidEnabled = false;
						s.fluidProperties = prop;
						s.cbTypes.add(cbType);
 
						s = new Polygon(
							[   Vec2.weak(736.5,130)   ,  Vec2.weak(729.5,143)   ,  Vec2.weak(728.5,167)   ,  Vec2.weak(740.5,221)   ,  Vec2.weak(744,125.5)   ],
							mat,
							filt
						);
						s.body = body;
						s.fluidEnabled = false;
						s.fluidProperties = prop;
						s.cbTypes.add(cbType);
 
						s = new Polygon(
							[   Vec2.weak(289,365.5)   ,  Vec2.weak(124,328)   ,  Vec2.weak(290.5,393)   ],
							mat,
							filt
						);
						s.body = body;
						s.fluidEnabled = false;
						s.fluidProperties = prop;
						s.cbTypes.add(cbType);
 
						s = new Polygon(
							[   Vec2.weak(744,125.5)   ,  Vec2.weak(740.5,221)   ,  Vec2.weak(754.5,112)   ],
							mat,
							filt
						);
						s.body = body;
						s.fluidEnabled = false;
						s.fluidProperties = prop;
						s.cbTypes.add(cbType);
 
						s = new Polygon(
							[   Vec2.weak(754.5,112)   ,  Vec2.weak(740.5,221)   ,  Vec2.weak(740,234)   ,  Vec2.weak(799.5,598)   ,  Vec2.weak(764.5,90)   ],
							mat,
							filt
						);
						s.body = body;
						s.fluidEnabled = false;
						s.fluidProperties = prop;
						s.cbTypes.add(cbType);
 
						s = new Polygon(
							[   Vec2.weak(290.5,393)   ,  Vec2.weak(124,328)   ,  Vec2.weak(298,406.5)   ],
							mat,
							filt
						);
						s.body = body;
						s.fluidEnabled = false;
						s.fluidProperties = prop;
						s.cbTypes.add(cbType);
 
						s = new Polygon(
							[   Vec2.weak(340,436.5)   ,  Vec2.weak(308.5,417)   ,  Vec2.weak(124,328)   ,  Vec2.weak(0,599.5)   ,  Vec2.weak(418,505)   ],
							mat,
							filt
						);
						s.body = body;
						s.fluidEnabled = false;
						s.fluidProperties = prop;
						s.cbTypes.add(cbType);
 
						s = new Polygon(
							[   Vec2.weak(82.5,196)   ,  Vec2.weak(10.5,58)   ,  Vec2.weak(0,599.5)   ,  Vec2.weak(111.5,300)   ],
							mat,
							filt
						);
						s.body = body;
						s.fluidEnabled = false;
						s.fluidProperties = prop;
						s.cbTypes.add(cbType);
 
						s = new Polygon(
							[   Vec2.weak(559.5,430)   ,  Vec2.weak(559.5,440)   ,  Vec2.weak(799.5,598)   ,  Vec2.weak(740,234)   ,  Vec2.weak(729,242)   ],
							mat,
							filt
						);
						s.body = body;
						s.fluidEnabled = false;
						s.fluidProperties = prop;
						s.cbTypes.add(cbType);
 
						s = new Polygon(
							[   Vec2.weak(298,406.5)   ,  Vec2.weak(124,328)   ,  Vec2.weak(308.5,417)   ],
							mat,
							filt
						);
						s.body = body;
						s.fluidEnabled = false;
						s.fluidProperties = prop;
						s.cbTypes.add(cbType);
 
						s = new Polygon(
							[   Vec2.weak(1,-0.5)   ,  Vec2.weak(0,599.5)   ,  Vec2.weak(10.5,58)   ],
							mat,
							filt
						);
						s.body = body;
						s.fluidEnabled = false;
						s.fluidProperties = prop;
						s.cbTypes.add(cbType);
 
						s = new Polygon(
							[   Vec2.weak(111.5,300)   ,  Vec2.weak(0,599.5)   ,  Vec2.weak(124,328)   ],
							mat,
							filt
						);
						s.body = body;
						s.fluidEnabled = false;
						s.fluidProperties = prop;
						s.cbTypes.add(cbType);
 
						s = new Polygon(
							[   Vec2.weak(418,505)   ,  Vec2.weak(0,599.5)   ,  Vec2.weak(452,519)   ],
							mat,
							filt
						);
						s.body = body;
						s.fluidEnabled = false;
						s.fluidProperties = prop;
						s.cbTypes.add(cbType);
 
						s = new Polygon(
							[   Vec2.weak(0,599.5)   ,  Vec2.weak(799.5,598)   ,  Vec2.weak(452,519)   ],
							mat,
							filt
						);
						s.body = body;
						s.fluidEnabled = false;
						s.fluidProperties = prop;
						s.cbTypes.add(cbType);
 
						s = new Polygon(
							[   Vec2.weak(452,519)   ,  Vec2.weak(799.5,598)   ,  Vec2.weak(498,503)   ],
							mat,
							filt
						);
						s.body = body;
						s.fluidEnabled = false;
						s.fluidProperties = prop;
						s.cbTypes.add(cbType);
 
						s = new Polygon(
							[   Vec2.weak(498,503)   ,  Vec2.weak(799.5,598)   ,  Vec2.weak(525.5,478)   ],
							mat,
							filt
						);
						s.body = body;
						s.fluidEnabled = false;
						s.fluidProperties = prop;
						s.cbTypes.add(cbType);
 
						s = new Polygon(
							[   Vec2.weak(525.5,478)   ,  Vec2.weak(799.5,598)   ,  Vec2.weak(555.5,448)   ],
							mat,
							filt
						);
						s.body = body;
						s.fluidEnabled = false;
						s.fluidProperties = prop;
						s.cbTypes.add(cbType);
 
						s = new Polygon(
							[   Vec2.weak(555.5,448)   ,  Vec2.weak(799.5,598)   ,  Vec2.weak(559.5,440)   ],
							mat,
							filt
						);
						s.body = body;
						s.fluidEnabled = false;
						s.fluidProperties = prop;
						s.cbTypes.add(cbType);
 
 
 
 
			anchor =  Vec2.get(400,300);
			body.translateShapes(Vec2.weak(-anchor.x,-anchor.y));
			body.position.setxy(0,0);
 
			bodies["ground"] = new BodyPair(body,anchor);
 
	}
}
}
 
import nape.phys.Body;
import nape.geom.Vec2;
 
class BodyPair {
	public var body:Body;
	public var anchor:Vec2;
	public function BodyPair(body:Body,anchor:Vec2):void {
		this.body = body;
		this.anchor = anchor;
	}
}

11 Comments »

  1. Great work on this tutorial. Thanks a lot for including all files including the PhysicsData file, other tutorials haven’t and have been a headache as with different versions of Nape and the PhysicsEditor actionscript generator can be difficult to reconcile which versions play nicely together.

    In response to your note: “NOTE: by the time you read this, this discrepancy may be fixed and none of this may be necessary. I’m currently using the 1.0.9 version of PhysicsEditor.”

    It seems that the latest version of PhysicsEditor(I’m using 1.0.10) actually plays a little worse with the latest version of Nape. After making the changes you suggested, I was still left with errors.

    I was able to reconcile what the problems were by comparing with your version of PhysicsData. I found two issues:

    1. In the ‘cbtype’ function, the line:
    if(name==”null”) return null;

    needs to be changed to:
    if(name==”null”) return CbType.ANY_BODY;

    2. In the ‘init’ function, the line:
    anchor = (true) ? body.localCOM.copy() : Vec2.get(0,600);

    needs to be changed to:
    anchor = Vec2.get(400,300);

    (This I assume this would need to be updated if the stage size were to change)

  2. Devon O. says:

    Hey Craig,

    Thank you for the comments. You’re right – I made some changes to the null conditional before writing up this blog post that I forgot to mention (didn’t have problems with the anchor though) – so thank you for pointing that info out to anyone who may be reading this.

    It turns out it gets even worse though. If you upgrade to Nape 2.0, the graphic property has been fully deprecated, so any references to that inside the nape.as template file must be removed as well.

    -d.

  3. Nape 2.0.3 with Starling 1.3 and PhysicsEditor 1.0.10…

    I’ve started looking into Starling (1.3), Nape (2.0.3), and PhysicsEditor (1.0.10) today and found that the tutorials/examples on the web don’t work with the current versions. Nothing new there, I’m sure in a few weeks (or months at the latest) my c…

  4. Michael says:

    Any chances of updating your tutorial to be compatible with Nape 2.0.3 and Starling 1.3? I’ve downloaded PE1.1.10 and can’t seem to reconcile the code to work…

  5. Devon O. says:

    I’ll try to make some time for an update this weekend.

  6. dimitri says:

    For a world with 1 square body (with square starling image) moving -500 pixels along the x axis, here the debug draw moves faster than the image.

    wonder why the debug draws and the starling images are not in sync (positions) when the velocity large – but are in perfect sync when they are at rest or in slow velocity.

    Would this not be a problem if we have 100 very fast moving objects like bullets.

  7. wuchao says:

    ret.graphic = graphic;
    ret.graphicUpdate = function(b:Body):void {
    var gp:Vec2 = b.localToWorld(offset);

    when i run ,worry here.

    (starling 1.3,nape:2.09,phsicyEditor 1.09)

  8. Devon O. says:

    Hey wuchao,

    As was mentioned (partially) in a previous comment, the latest version of Nape no longer contains the graphic or graphicUpdate properties on Body objects. You will have to either remove those from the PhysicsEditor Nape template or remove those references from the generated class file.

  9. allandt says:

    LOVE this – thanks for the tute

  10. Rod says:

    User this PE Nape as3 template with Starling 1.3 and Nape 2.0.9
    Regards
    Rod

    package {

    import nape.phys.Body;
    import nape.phys.BodyType;
    import nape.shape.Shape;
    import nape.shape.Polygon;
    import nape.shape.Circle;
    import nape.geom.Vec2;
    import nape.dynamics.InteractionFilter;
    import nape.phys.Material;
    import nape.phys.FluidProperties;
    import nape.callbacks.CbType;
    import nape.geom.AABB;

    import flash.display.DisplayObject;
    import flash.geom.Rectangle;
    import flash.utils.Dictionary;

    public class PhysicsData {

    public static function createBody(name:String,graphic:DisplayObject=null):Body {
    var xret:BodyPair = lookup(name);
    if(graphic==null) return xret.body.copy();

    var ret:Body = xret.body.copy();
    graphic.x = graphic.y = 0;
    graphic.rotation = 0;
    var bounds:Rectangle = graphic.getBounds(graphic);
    var offset:Vec2 = Vec2.get(bounds.x-xret.anchor.x, bounds.y-xret.anchor.y);

    ret.userData.graphic = graphic;
    ret.userData.graphicUpdate = function(b:Body):void {
    var gp:Vec2 = b.localPointToWorld(offset);
    b.userData.graphic.x = gp.x;
    b.userData.graphic.y = gp.y;
    b.userData.graphic.rotation = (b.rotation*180/Math.PI)%360;
    }

    return ret;
    }

    public static function registerMaterial(name:String,material:Material):void {
    if(materials==null) materials = new Dictionary();
    materials[name] = material;
    }
    public static function registerFilter(name:String,filter:InteractionFilter):void {
    if(filters==null) filters = new Dictionary();
    filters[name] = filter;
    }
    public static function registerFluidProperties(name:String,properties:FluidProperties):void {
    if(fprops==null) fprops = new Dictionary();
    fprops[name] = properties;
    }
    public static function registerCbType(name:String,cbType:CbType):void {
    if(types==null) types = new Dictionary();
    types[name] = cbType;
    }

    //———————————————————————-

    private static var bodies :Dictionary;
    private static var materials:Dictionary;
    private static var filters :Dictionary;
    private static var fprops :Dictionary;
    private static var types :Dictionary;
    private static function material(name:String):Material {
    if(name==”default”) return new Material();
    else {
    if(materials==null || materials[name] === undefined)
    throw “Error: Material with name ‘”+name+”‘ has not been registered”;
    return materials[name] as Material;
    }
    }
    private static function filter(name:String):InteractionFilter {
    if(name==”default”) return new InteractionFilter();
    else {
    if(filters==null || filters[name] === undefined)
    throw “Error: InteractionFilter with name ‘”+name+”‘ has not been registered”;
    return filters[name] as InteractionFilter;
    }
    }
    private static function fprop(name:String):FluidProperties {
    if(name==”default”) return new FluidProperties();
    else {
    if(fprops==null || fprops[name] === undefined)
    throw “Error: FluidProperties with name ‘”+name+”‘ has not been registered”;
    return fprops[name] as FluidProperties;
    }
    }
    private static function cbtype(name:String):CbType {
    if(name==”null”) return CbType.ANY_BODY;
    else {
    if(types==null || types[name] === undefined)
    throw “Error: CbType with name ‘”+name+”‘ has not been registered”;
    return types[name] as CbType;
    }
    }

    private static function lookup(name:String):BodyPair {
    if(bodies==null) init();
    if(bodies[name] === undefined) throw “Error: Body with name ‘”+name+”‘ does not exist”;
    return bodies[name] as BodyPair;
    }

    //———————————————————————-

    private static function init():void {
    bodies = new Dictionary();

    var body:Body;
    var mat:Material;
    var filt:InteractionFilter;
    var prop:FluidProperties;
    var cbType:CbType;
    var s:Shape;
    var anchor:Vec2;

    {% for body in bodies %}
    body = new Body();
    body.cbTypes.add(cbtype(“{{body.cbType}}”));

    {% for fixture in body.fixtures %}
    mat = material(“{{fixture.material}}”);
    filt = filter(“{{fixture.filter}}”);
    prop = fprop(“{{fixture.fprop}}”);
    cbType = cbtype(“{{fixture.cbType}}”);

    {% if fixture.isCircle %}
    s = new Circle(
    {{fixture.radius}},
    Vec2.weak({{fixture.center.x}},{{fixture.center.y}}),
    mat,
    filt
    );
    s.body = body;
    s.fluidEnabled = {{fixture.fluidEnabled}};
    s.fluidProperties = prop;
    s.cbTypes.add(cbType);
    {% else %}
    {% for polygon in fixture.polygons %}
    s = new Polygon(
    [ {% for point in polygon %} {% if not forloop.first %}, {% endif %} Vec2.weak({{point.x}},{{point.y}}) {% endfor %} ],
    mat,
    filt
    );
    s.body = body;
    s.fluidEnabled = {{fixture.fluidEnabled}};
    s.fluidProperties = prop;
    s.cbTypes.add(cbType);
    {% endfor %}
    {% endif %}
    {% endfor %}

    anchor = ({{body.auto_anchor}}) ? body.localCOM.copy() : Vec2.get({{body.anchorPointAbs.x}},{{body.anchorPointAbs.y}});
    body.translateShapes(Vec2.weak(-anchor.x,-anchor.y));
    body.position.setxy(0,0);

    bodies[“{{body.name}}”] = new BodyPair(body,anchor);
    {% endfor %}
    }
    }
    }

    import nape.phys.Body;
    import nape.geom.Vec2;

    class BodyPair {
    public var body:Body;
    public var anchor:Vec2;
    public function BodyPair(body:Body,anchor:Vec2):void {
    this.body = body;
    this.anchor = anchor;
    }
    }

  11. Lex says:

    In the above template you should…

    CHANGE:

    import flash.display.DisplayObject;

    TO:

    import starling.display.DisplayObject;

    Hope this helps someone.

    Lex

RSS feed for comments on this post. / TrackBack URI

Leave a Reply

Devon O. Wolfgang

Technical Reviewer of “The Essential Guide to Flash CS4 AIR Development”

Contributing Author of “Flash AS3 for Interactive Agencies”

Senior Software Engineer at Meez

Starling Particle Editor

vignette

Some Photographic Shaders


A couple weeks ago I was contacted and asked to develop some filters for Starling that could be used in a mobile camera app[…]

boids

Animated Particles, Books, and Code – It’s a New Year


It’s a new year[…]

bug

Logical Or Assignment Bug in ASC2


So, here’s something to keep an eye on if switching to AIR 3.8[…]

Starling Filter Collection

Starling Filter Collection


Building up a collection of filters for the Starling framework[…]

Starling Warp

Warp Filter for Starling


Another filter for the Starling framework[…]

promise

Promises Promises


What it boils down to is handling asynchronous tasks […] in a clean, intelligent fashion […]

GodRays

Starling ‘God Ray’ Filter


While cruising the internet today looking for interesting things to try out I ran across this fun little GPU Gem[…]

Alpha in Starling Filters and Basic Branching in AGAL


In plain English to create a circular mask we would want to do something like this[…]

Starling, Nape Physics, and PhysicsEditor


A look at using the PhysicsEditor tool for Nape and Starling […]

Playing With a Couple Game Ideas


Just a couple game fragments, really[…]

One More Filter For Starling


Another filter for the Starling framework[…]

Filters in Starling


Using and writing filters in the Starling framework[…]

Towards a Better Scratch


Perhaps it was too much Meat Beat Manifesto in the late 80’s […]

Learning AGAL with AGALMacroAssembler and OpenGL Examples

So the other day I sat down and thought to myself: self, it’s high time you learn you some of this new fancy pants AGAL[…]

UV Scrolling in Starling


Obviously this could come in pretty darned handy for space games, side scrollers, etc, etc[…]

Drawing on Stuff in Away3D 4.0

So, Easter Day, I thought I’d sit down and make a little ‘Paint on an Egg and Send it to Your Friend’ app.