Simulate planet gravity with Phaser + Box2D as seen on Angry Birds Space

Read all posts about "" game

I am sure you are playing Angry Birds Fight! during these days. I do, and having a new Angry Bird game on my phone reminded me of the old Angry Birds Space and the AS3+Box2D tutorial I made three years ago.

Following the same concept, I made the same thing using Phaser and the Box2D plugin. This is what I created with just a few lines:

Here we have two planets with their gravity zones, click anywhere on the stage to place a crate and watch it fall on the planet or remain floating in the space.

The source code is really easy:

var game;

// groups containing crates and planets

var crateGroup;
var planetGroup;

// a force reducer to let the simulation run smoothly

var forceReducer = 0.005;

// graphic object where to draw planet gravity area

var gravityGraphics;

window.onload = function() {	
	game = new Phaser.Game(800, 600, Phaser.AUTO, "");
     game.state.add("PlayGame",playGame);
     game.state.start("PlayGame");
}
	
var playGame = function(game){};

playGame.prototype = {
	preload: function(){
		game.load.image("crate", "crate.png");
		game.load.image("planet", "planet.png");
		game.load.image("bigplanet", "bigplanet.png"); 
	},
  	create: function(){
  		
  		// adding groups
  		
  		crateGroup = game.add.group();
  		planetGroup = game.add.group();
  		
		// adding graphic objects
		
		gravityGraphics = game.add.graphics(0, 0);
    		gravityGraphics.lineStyle(2,0xffffff,0.5);
  		
		// stage setup
		
		game.stage.backgroundColor = "#222222";
		
		// physics initialization
		
		game.physics.startSystem(Phaser.Physics.BOX2D);
    		
		// adding a couple of planets. Arguments are:
		// x position
		// y position
		// gravity radius
		// gravity force
		// graphic asset
    		
		addPlanet(180, 200, 250, 150, "planet");
    		addPlanet(570, 350, 400, 250, "bigplanet");
		
		// waiting for player input
    		
		game.input.onDown.add(addCrate, this);
	},
	update: function(){
	
		// looping through all crates
	
		for(var i=0;i<crateGroup.total;i++){	
			var c = crateGroup.getChildAt(i);
			
			// looping through all planets
			
			for(var j=0;j<planetGroup.total;j++){ 
				var p = planetGroup.getChildAt(j);
				
				// calculating distance between the planet and the crate
				
				var distance = Phaser.Math.distance(c.x,c.y,p.x,p.y);
				
				// checking if the distance is less than gravity radius
				
				if(distance<p.width/2+p.gravityRadius/2){
					
					// calculating angle between the planet and the crate
					
					var angle = Phaser.Math.angleBetween(c.x,c.y,p.x,p.y);
					
					// add gravity force to the crate in the direction of planet center
					
					c.body.applyForce(p.gravityForce*Math.cos(angle)*forceReducer,p.gravityForce*Math.sin(angle)*forceReducer);
				}
			}
		}
	}
}

// function to add a crate

function addCrate(e){	
	var crateSprite = game.add.sprite(e.x, e.y, "crate");
	crateGroup.add(crateSprite);
    	game.physics.box2d.enable(crateSprite);
}

// function to add a planet

function addPlanet(posX, posY, gravityRadius, gravityForce, asset){
	var planet = game.add.sprite(posX, posY, asset);
	planet.gravityRadius = gravityRadius;
	planet.gravityForce = gravityForce
	planetGroup.add(planet);
	game.physics.box2d.enable(planet);
	planet.body.static = true;
	
	// look how I create a circular body
	
	planet.body.setCircle(planet.width / 2);
	gravityGraphics.drawCircle(planet.x, planet.y, planet.width+planet.gravityRadius);
}

And here we have our planet gravity made with Phaser and Box2D. As usual you can 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

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