Creation of an hook using Nape Physics Engine and Distance Joint

Read all posts about "" game

Since the creation of a Box2D hook like the one seen on iOS Mikey Hooks game was quite interesting, I got some message and email asking me to do the same thing with Nape Physics Engine which seems to perform better on mobile devices.

Here it is, I kept the same comments and the same function name and order to let you compare the scripts:

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;
	import nape.shape.ShapeList;
	import nape.constraint.DistanceJoint;
	import nape.constraint.Constraint;

	public class Main extends Sprite {
		private var napeWorld:Space=new Space(new Vec2(0,500));
		private var hero:Body;
		private var distanceJoint:DistanceJoint;
		private var debug:ShapeDebug=new ShapeDebug(640,480,0xffffff);
		private var napeDebugSprite:Sprite=new Sprite();
		private var isHooked:Boolean=false;
		public function Main():void {
			// this is the ground
			addBox(320,480,640,20,BodyType.STATIC);
			// let's add some random stuff
			for (var i:Number=1; i<=12; i++) {
				addBox(Math.random()*600+20,Math.random()*300,Math.random()*30+15,Math.random()*30+15,BodyType.STATIC);
			}
			// and finally the hero
			hero=addBox(320,460,20,20,BodyType.DYNAMIC);
			addEventListener(Event.ENTER_FRAME,update);
			stage.addEventListener(MouseEvent.MOUSE_DOWN,fireHook);
			stage.addEventListener(MouseEvent.MOUSE_UP,releaseHook);
			addChild(napeDebugSprite);
			debug.drawConstraints=true;
			napeDebugSprite.addChild(debug.display);
		}
		private function fireHook(e:MouseEvent):void {
			// when firing the hook, let's remove old joints, if any
			if (distanceJoint) {
				napeWorld.constraints.remove(distanceJoint);
			}
			// checking the body under the mouse;
			var bodies:BodyList=napeWorld.bodiesUnderPoint(new Vec2(mouseX,mouseY));
			if (bodies.length==1) {
				// if I have a body under the mouse, I create a distance joint between the hero and the body itself
				var body:Body=bodies.at(0);
				if (body.isStatic()) {
					distanceJoint=new DistanceJoint(body,hero,new Vec2(0,0),new Vec2(0,0),0,Vec2.distance(body.position,hero.position));
					distanceJoint.space=napeWorld;
					isHooked=true
				}
			}
		}
		private function releaseHook(e:MouseEvent):void {
			// if I release the mouse, I destroy the distance joint
			if (distanceJoint) {
				napeWorld.constraints.remove(distanceJoint);
				isHooked=false;
			}
		}
		private function manageHook():void{
            // as long as the hook is active, I shorten a bit joint distance
            if (isHooked) {
                distanceJoint.jointMax=distanceJoint.jointMax*0.99
            }
        } 
		private function addBox(pX:Number,pY:Number,w:Number,h:Number,bodyType:BodyType):Body {
			var body:Body=new Body(bodyType,new Vec2(pX,pY));
			var polygon:Polygon=new Polygon(Polygon.box(w,h));
			polygon.material.elasticity=0.5;
			polygon.material.density=1;
			polygon.material.staticFriction=0;
			body.shapes.add(polygon);
			body.space=napeWorld;
			return body;
		}
		private function update(e:Event):void {
			napeWorld.step(1/30,10,10);
			manageHook()
			debug.clear();
			debug.draw(napeWorld);
			debug.flush();
		}
	}
}

And this is the result:

Click and hold your mouse over a static body to create a hook and rewind it, release mouse button to destroy the hook. Try to swing like a tarzan geek, again

Download the source code. Which one would you use? Nape or Box2D?

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

215 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
// Stairs
// 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