How to simulate flocking behavior with Boids using HTML5 and Phaser

Read all posts about "" game
I bet you don’t know what Boids are. From Wikipedia: Boids is an artificial life program, developed by Craig Reynolds in 1986, which simulates the flocking behaviour of birds. The name “boid” corresponds to a shortened version of “bird-oid object”, which refers to a bird-like object. I am going to show you, in a series of posts, how to simulate a flocking behavior and how to use it in other projects which have nothing to do with flocking. First, a couple of references: you may find interesting the official Boids page by Craig Reynolds, and also the pseudo code by Conrad Parker. We’ll divide the tutorial step by step, and in the first step we’ll see how to accomplish to the first Boids rule. Rule 1: Boids try to fly towards the centre of mass of neighbouring boids. In other words, each boid will try to fly towards the average position of all other boids. It’s quite easy thanks to Phaser Point class and Arcade Physics. At each frame, boids trajectory is adjusted. Obviously a Boid can’t see all the other boids, but only the ones within a given range. Look at the example – you may need to reload it if you only see a white ball:
Boids converge to the center of the flock, and if you notice some boids wandering like crazy, that’s because they are too far from any other visible boid. This is the commented source code:
var game;

// number of boids (bird-oid objects)
var boidsAmount = 50;
// speed of each boid, in pixels per second
var boidSpeed = 100;
// radius of sight of the boid
var boidRadius = 50;
// array which will contain all boids
var boids = [];

window.onload = function() {	
	game = new Phaser.Game(640, 640, Phaser.AUTO, "");
     game.state.add("Simulate", simulate);
     game.state.start("Simulate");
}

var simulate = function(game){};
simulate.prototype = {
     preload: function(){
          // preloading boid image
          game.load.image("boid", "boid.png");     
     },
     create: function(){
          for(var i = 0; i < boidsAmount; i++){
               // placing the boid at a random point within the canvas
               var randomPoint = new Phaser.Point(game.rnd.between(0, game.width - 1), game.rnd.between(0, game.height - 1));
               boids[i] = {
                    position: randomPoint,
                    asset: game.add.sprite(randomPoint.x, randomPoint.y, "boid")
               }
               boids[i].asset.anchor.set(0.5);
               // enabling boid physics
               game.physics.enable(boids[i].asset, Phaser.Physics.ARCADE);
               // allowing us to manually rotate the boid
               boids[i].asset.body.allowRotation = false;     
          }
     },
     update: function(){
          // temp array to calculate centroid 
          var centroidArray = [];
          // looping through each boid
          for(var i = 0; i < boidsAmount; i++){
               // for each boid, looping through each boid
               for(var j = 0; j < boidsAmount; j++){
                    // if the boid is not the current boid and the boid is within boid radius...
                    if(i != j &amp;&amp; boids[i].position.distance(boids[j].position) < boidRadius){
                         // pushing the boid into centroid array
                         centroidArray.push(boids[j].position);     
                    }
               }
               // if centroidArray is populated, that is if there were boids nearby the current boid...
               if(centroidArray.length &gt; 0){
                    // calculating the centroid
                    var centroid = Phaser.Point.centroid(centroidArray);
               }
               else{
                    // just tossing a random point
                    var centroid = new Phaser.Point(game.rnd.between(0, game.width - 1), game.rnd.between(0, game.height - 1));
               }
               // rotating the boid towards the centroid
               boids[i].asset.angle = boids[i].position.angle(centroid, true);
               // moving the boid towards the centroid
               game.physics.arcade.moveToXY(boids[i].asset, centroid.x, centroid.y, boidSpeed);
               // updating boid position
               boids[i].position.set(boids[i].asset.x, boids[i].asset.y);
          }                    
     }     
}
This was just the beginning as there are two more steps to develop, meanwhile 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

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