Way of an Idea prototype updated to Box2D 2.1a and Nape

Read all posts about "" game

Three years ago I published a three steps tutorial about the creation of a Flash game like Way of an Idea.

Following the same concepts I already explained in steps 1, 2 and 3, here is the updated Box2D 2.1a version running together with the Nape version of the game.

This is what we have:

Draw the track with your mouse, press SPACE to play/pause the simulation and delete the chalk pressing 0 (zero) and moving the mouse over the chalk.

You should be able to recognize both debug draws, Box2D and Nape.

This is the source code, with comments to show which part of the code belongs to Box2D and which to Nape:

package {
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.KeyboardEvent;
	// BOX2D
	import Box2D.Dynamics.*;
	import Box2D.Collision.*;
	import Box2D.Collision.Shapes.*;
	import Box2D.Common.Math.*;
	// NAPE
	import nape.geom.Vec2;
	import nape.phys.Body;
	import nape.phys.BodyList;
	import nape.phys.BodyType;
	import nape.shape.Polygon;
	import nape.shape.Circle;
	import nape.space.Space;
	import nape.util.ShapeDebug;
	public class Main extends Sprite {
		private var drawing:Boolean=false;
		private var canvas:Sprite = new Sprite();
		private var pointsArray:Array;
		private var pixelDist:int=20;
		private var savedX:int;
		private var savedY:int;
		private var timeStep:Number=0;
		// BOX2D
		private var world:b2World=new b2World(new b2Vec2(0,10),true);
		private var worldScale:Number=30;
		private var debugSprite:Sprite=new Sprite();
		// NAPE
		private var napeWorld:Space=new Space(new Vec2(0,500));
		private var debug:ShapeDebug=new ShapeDebug(640,480,0x00ff00);
		private var napeDebugSprite:Sprite=new Sprite();
		public function Main():void {
			addChild(canvas);
			canvas.graphics.lineStyle(5);
			stage.addEventListener(MouseEvent.MOUSE_DOWN,mousePressed);
			stage.addEventListener(MouseEvent.MOUSE_MOVE,mouseMoved);
			stage.addEventListener(MouseEvent.MOUSE_UP,mouseReleased);
			addEventListener(Event.ENTER_FRAME,update);
			stage.addEventListener(KeyboardEvent.KEY_DOWN,keyPressed);
			// BOX2D
			addChild(debugSprite);
			debugDraw();
			// NAPE
			addChild(napeDebugSprite);
			napeDebugSprite.addChild(debug.display);
			// BOX2D;
			var bodyDef:b2BodyDef= new b2BodyDef();
			bodyDef.type=b2Body.b2_dynamicBody;
			bodyDef.position.Set(20/worldScale,20/worldScale);
			var circleShape:b2CircleShape = new b2CircleShape(15/worldScale);
			var fixtureDef:b2FixtureDef = new b2FixtureDef();
			fixtureDef.density=1;
			fixtureDef.friction=0.5;
			fixtureDef.restitution=0.5;
			fixtureDef.shape=circleShape;
			var body:b2Body=world.CreateBody(bodyDef);
			body.CreateFixture(fixtureDef);
			// NAPE
			var napeBody:Body=new Body(BodyType.DYNAMIC,new Vec2(20,20));
			var circle:Circle=new Circle(15);
			circle.material.elasticity=0.5;
			circle.material.density=1;
			circle.material.staticFriction=0.5;
			napeBody.shapes.add(circle);
			napeBody.space=napeWorld;
		}
		private function mousePressed(e:MouseEvent):void {
			drawing=true;
			canvas.graphics.moveTo(mouseX,mouseY);
			pointsArray=new Array();
			savedX=mouseX;
			savedY=mouseY;
			pointsArray.push(savedX);
			pointsArray.push(savedY);
		}
		private function mouseMoved(e:MouseEvent):void {
			if (drawing) {
				var distX:int=mouseX-savedX;
				var distY:int=mouseY-savedY;
				if (distX*distX+distY*distY>pixelDist*pixelDist) {
					canvas.graphics.lineTo(mouseX,mouseY);
					savedX=mouseX;
					savedY=mouseY;
					pointsArray.push(savedX);
					pointsArray.push(savedY);
				}
			}
		}
		// BOX2D
		private function debugDraw():void {
			var debugDraw:b2DebugDraw=new b2DebugDraw();
			debugDraw.SetSprite(debugSprite);
			debugDraw.SetDrawScale(worldScale);
			debugDraw.SetFlags(b2DebugDraw.e_shapeBit|b2DebugDraw.e_jointBit);
			debugDraw.SetFillAlpha(0.5);
			world.SetDebugDraw(debugDraw);
		}
		private function mouseReleased(e:MouseEvent):void {
			drawing=false;
			var sx:int;
			var ex:int;
			var sy:int;
			var ey:int;
			var distX:int;
			var distY:int;
			var dist:Number;
			var angle:Number;
			var segments:int=pointsArray.length/2-1;
			for (var i:int=0; i0) {
					for (var i:int = 0; i < bodies.length; i++) {
						var body:Body=bodies.at(i);
						if (body.type==BodyType.STATIC) {
							napeWorld.bodies.remove(body);
						}
					}
				}
			}
		}
		private function addPath(pX:Number,pY:Number,w:Number,h:Number,angle:Number):void {
			// BOX2D
			var bodyDef:b2BodyDef= new b2BodyDef();
			var polygonShape:b2PolygonShape = new b2PolygonShape();
			polygonShape.SetAsOrientedBox(w/2/worldScale, h/2/worldScale, new b2Vec2(pX/worldScale,pY/worldScale),angle);
			var fixtureDef:b2FixtureDef = new b2FixtureDef();
			fixtureDef.density=1;
			fixtureDef.friction=0.5;
			fixtureDef.restitution=0.5;
			fixtureDef.shape=polygonShape;
			var body:b2Body=world.CreateBody(bodyDef);
			body.CreateFixture(fixtureDef);
			// NAPE
			var napeBody:Body=new Body(BodyType.STATIC,new Vec2(pX,pY));
			var polygon:Polygon=new Polygon(Polygon.box(w,h));
			polygon.rotate(angle);
			polygon.material.elasticity=0.5;
			polygon.material.density=1;
			polygon.material.staticFriction=0.5;
			napeBody.shapes.add(polygon);
			napeBody.space=napeWorld;
		}
		// BOX2D
		private function queryCallback(fixture:b2Fixture):Boolean {
			var touchedBody:b2Body=fixture.GetBody();
			for (var f:b2Fixture=touchedBody.GetFixtureList(); f; f=f.GetNext()) {
				if (touchedBody.GetType()==b2Body.b2_staticBody) {
					world.DestroyBody(touchedBody);
				}
			}
			return false;
		}
		private function update(e:Event):void {
			if (timeStep) {
				// BOX2D
				world.Step(1/30,10,10);
				world.ClearForces();
				// NAPE
				napeWorld.step(1/30,10,10);
			}
			// BOX2D
			world.DrawDebugData();
			// NAPE
			debug.clear();
			debug.draw(napeWorld);
			debug.flush();
		}
	}
}

It would be interesting to know if you ever used Nape in some of your projects, meanwhile download the full source code of the prototype.

Get the most popular Phaser 3 book

Through 202 pages, 32 source code examples and an Android Studio project you will learn how to build cross platform HTML5 games and create a complete game along the way.

Get the book

214 GAME PROTOTYPES EXPLAINED WITH SOURCE CODE
// 1+2=3
// 100 rounds
// 10000000
// 2 Cars
// 2048
// A Blocky Christmas
// A Jumping Block
// A Life of Logic
// Angry Birds
// Angry Birds Space
// Artillery
// Astro-PANIC!
// Avoider
// Back to Square One
// Ball Game
// Ball vs Ball
// Ball: Revamped
// Balloon Invasion
// BallPusher
// Ballz
// Bar Balance
// Bejeweled
// Biggification
// Block it
// Blockage
// Bloons
// Boids
// Bombuzal
// Boom Dots
// Bouncing Ball
// Bouncing Ball 2
// Bouncy Light
// BoxHead
// Breakout
// Bricks
// Bubble Chaos
// Bubbles 2
// Card Game
// Castle Ramble
// Chronotron
// Circle Chain
// Circle Path
// Circle Race
// Circular endless runner
// Cirplosion
// CLOCKS - The Game
// Color Hit
// Color Jump
// ColorFill
// Columns
// Concentration
// Crossy Road
// Crush the Castle
// Cube Jump
// CubesOut
// Dash N Blast
// Dashy Panda
// Deflection
// Diamond Digger Saga
// Don't touch the spikes
// Dots
// Down The Mountain
// Drag and Match
// Draw Game
// Drop Wizard
// DROP'd
// Dudeski
// Dungeon Raid
// Educational Game
// Elasticity
// Endless Runner
// Erase Box
// Eskiv
// Farm Heroes Saga
// Filler
// Flappy Bird
// Fling
// Flipping Legend
// Floaty Light
// Fuse Ballz
// GearTaker
// Gem Sweeper
// Globe
// Goat Rider
// Gold Miner
// Grindstone
// GuessNext
// Helicopter
// Hero Emblems
// Hero Slide
// Hexagonal Tiles
// HookPod
// Hop Hop Hop Underwater
// Horizontal Endless Runner
// Hundreds
// Hungry Hero
// Hurry it's Christmas
// InkTd
// Iromeku
// Jet Set Willy
// Jigsaw Game
// Knife Hit
// Knightfall
// Legends of Runeterra
// Lep's World
// Line Rider
// Lumines
// Magick
// MagOrMin
// Mass Attack
// Math Game
// Maze
// Meeblings
// Memdot
// Metro Siberia Underground
// Mike Dangers
// Mikey Hooks
// Nano War
// Nodes
// o:anquan
// One Button Game
// One Tap RPG
// Ononmin
// Pacco
// Perfect Square!
// Perfectionism
// Phyballs
// Pixel Purge
// PixelField
// Planet Revenge
// Plants Vs Zombies
// Platform
// Platform game
// Plus+Plus
// Pocket Snap
// Poker
// Pool
// Pop the Lock
// Pop to Save
// Poux
// Pudi
// Pumpkin Story
// Puppet Bird
// Pyramids of Ra
// qomp
// Quick Switch
// Racing
// Radical
// Rebuild Chile
// Renju
// Rise Above
// Risky Road
// Roguelike
// Roly Poly
// Run Around
// Rush Hour
// SameGame
// SamePhysics
// Save the Totem
// Security
// Serious Scramblers
// Shrink it
// Sling
// Slingy
// Snowflakes
// Sokoban
// Space Checkers
// Space is Key
// Spellfall
// Spinny Gun
// Splitter
// Spring Ninja
// Sproing
// Stabilize!
// Stack
// Stick Hero
// String Avoider
// Stringy
// Sudoku
// Super Mario Bros
// Surfingers
// Survival Horror
// Talesworth Adventure
// Tetris
// The Impossible Line
// The Moops - Combos of Joy
// The Next Arrow
// Threes
// Tic Tac Toe
// Timberman
// Tiny Wings
// Tipsy Tower
// Toony
// Totem Destroyer
// Tower Defense
// Trick Shot
// Tunnelball
// Turn
// Turnellio
// TwinSpin
// vvvvvv
// Warp Shift
// Way of an Idea
// Whack a Creep
// Wheel of Fortune
// Where's my Water
// Wish Upon a Star
// Word Game
// Wordle
// Worms
// Yanga
// Yeah Bunny
// Zhed
// zNumbers