HTML5 + Box2D hook like the one seen on iOS Mikey Hooks game

Read all posts about "" game
It’s being a long time since I showed you how to create a hook like the one used in Mikey Hooks using AS3 + Box2D and AS3 + Nape. It’s still a great game concept, so let me show you how to create the same thing using Box2D + Phaser. Despite being an extremely good looking effect, it’s very easy to create an hook using Box2D, you just have to play with distance joints. Let’s have a look at what we are going to do in a few lines of code:
You can’t control the ball, but click and hold the mouse on a static green body to fire the hook, release to destroy it. Here is the commented source code, have a look at it, you will be impressed about how easy can be the creation of this effect.
// the game itself
var game;

// the ball
var ballBody;

// the joint
var ballJoint;

// function to be executed when the window loads
window.onload = function() {	
     // starting the game itself
	game = new Phaser.Game(800, 600, Phaser.AUTO, "");
     // creation and execution of "PlayGame" state
     game.state.add("PlayGame",playGame);
     game.state.start("PlayGame");
}

var playGame = function(game){};

playGame.prototype = {
     // function to be executed onche game has been created
  	create: function(){
          // initializing Box2D physics
		game.physics.startSystem(Phaser.Physics.BOX2D);
          // making the debug draw show joints
          game.physics.box2d.debugDraw.joints = true;          
          // setting gravity
          game.physics.box2d.gravity.y = 500;
          // the ground
          var groundBody = new Phaser.Physics.Box2D.Body(game, null, 400, 595, 1);
          groundBody.setRectangle(800, 10, 0, 0);
          // adding some random bodies
          for(var i = 0; i < 10; i++){
               var randomBody =  new Phaser.Physics.Box2D.Body(game, null, game.rnd.between(100, 700), game.rnd.between(100, 400), 0);  
               randomBody.setRectangle(game.rnd.between(27, 75), game.rnd.between(25, 75), 0, 0);  
          }
          // the ball
          ballBody = new Phaser.Physics.Box2D.Body(game, null, 400, 550, 2);
          ballBody.setCircle(10);
          // waiting for player input then call addHook function
          game.input.onDown.add(addHook);
	},
     render: function(){
          // this is the debug draw in action
          game.debug.box2dWorld();
     },
     update: function(){
          // if there is a joint, make it shorter by 1%
          if(ballJoint){
               ballJoint.SetLength(ballJoint.GetLength() * 0.99);
          }
     }
}

function addHook(e){
     // this is how we get an array of bodies at a certain cordinate, in this case player input coordinate
	var currentBody = game.physics.box2d.getBodiesAtPoint(e.x, e.y);
	// if there is at least one body (but it can't be more than one in this example)...
	if(currentBody.length&gt;0){	
		// if the body is not static (it's not the ground)
		if(currentBody[0].static){
               // waking up the body (it won't work on a sleeping body)
               ballBody.data.SetAwake(true);  
               // adding a distance joint
               ballJoint = game.physics.box2d.distanceJoint(ballBody, currentBody[0]);     
          }
          // update listeners
          game.input.onDown.remove(addHook);
          game.input.onUp.add(removeHook);
     }
}

function removeHook(){
     // update listeners
     game.input.onUp.remove(removeHook);
     game.input.onDown.add(addHook);
     // destroying the joint
     game.physics.box2d.world.DestroyJoint(ballJoint);
          
}
I have a minigame concept in mind to show you, meanwhile download the source code.

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