Adding, removing and skinning bodies with NAPE

With the increasing popularity and development of NAPE, which now reaches version 2.0, it’s time to start looking at it and writing some tutorials.

I already showed you a quick comparation between Box2D and Nape in Box2D Vs Nape: Hello both worlds, today I am showing you how to create and destroy a box with a mouse click, and how to skin bodies.

So if you click with the mouse on this movie you will:

* Create a crate if you clicked on an empty space
* Destroy a crate if you clicked on it

And the whole thing is managed by this script:

package {
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import nape.geom.Vec2;
	import nape.phys.Body;
	import nape.phys.BodyList;
	import nape.phys.BodyType;
	import nape.shape.Polygon;
	import nape.space.Space;
	import nape.util.ShapeDebug;
	public class Main extends Sprite {
		// world creation with gravity
		private var world:Space=new Space(new Vec2(0,500));
		public function Main() {
			// static body creation with origin at pixels 320,500
			var staticFloor:Body=new Body(BodyType.STATIC,new Vec2(320,500));
			// new 640x40 box creation
			var floor:Polygon=new Polygon(Polygon.box(640,40));
			// elasticity property, similar to Box2D restitution
			floor.material.elasticity=0.5;
			// adding polygon to body
			staticFloor.shapes.add(floor);
			// adding body to world
			staticFloor.space=world;
			addEventListener(Event.ENTER_FRAME, update);
			stage.addEventListener(MouseEvent.CLICK,handleClick);
		}
		private function handleClick(e:MouseEvent):void {
			// getting all bodies at a given point (mouse coords)
			var bodies:BodyList=world.bodiesUnderPoint(new Vec2(mouseX,mouseY));
			// if any...
			if (bodies.length>0) {
				for (var i:int = 0; i < bodies.length; i++) {
					// getting the body
					var body:Body=bodies.at(i);
					// destroying it and removing its graphic asset if dynamic
					// we don't want to remove the floor although it's outside the stage
					if (body.type==BodyType.DYNAMIC) {
						removeChild(body.userData.sprite);
						world.bodies.remove(body);
					}
				}
			}
			else {
				// creation of a dynamic body, same thing as the static floor
				var dynamicBox:Body=new Body(BodyType.DYNAMIC,new Vec2(mouseX,mouseY));
				var block:Polygon=new Polygon(Polygon.box(50,50));
				block.material.elasticity=0.5;
				block.material.density=1;
				dynamicBox.shapes.add(block);
				// setting its custom data
				dynamicBox.userData.sprite=new Crate();
				addChild(dynamicBox.userData.sprite);
				dynamicBox.space=world;
			}
		}
		private function update(e:Event):void {
			world.step(1/30,10,10);
			// looping though bodies
			var bodies:BodyList=world.bodies;
			for (var i:int = 0; i < bodies.length; i++) {
				var body:Body=bodies.at(i);
				if(body.userData.sprite!=null){
					// adjusting graphic asset position
					body.userData.sprite.x=body.position.x
					body.userData.sprite.y=body.position.y
					body.userData.sprite.rotation=body.rotation*57.2957795;
				}
			}
		}
	}
}

Set up your NAPE project using the swc in the official download page and start playing with it.

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