Understanding steering behavior: HTML5 example using Phaser

Read all posts about "" game
In a previous post I showed you how to simulate flocking behavior with Boids using HTML5 and Phaser. There are a lot of things you can do with boids, and one of these nice things is the creation of a steering behavior. When a moving body has to change its direction to go towards a point, in real world it never stop moving in its old direction to suddenly move towards target point, but it gently steers until current direction matches to preferred direction, which is usually following the straight line from the boid to the target. Look at this example:
Here the boids steer to reach the target point – the red dot – making the movement more realistic than just following a straight line. As you can see in the source code, everything is just a matter of vector operations. Phaser does not features a vector class but we can rely on Point class which has a lot of methods we can use to handle Points as if they were vectors. Look at the commented source code:
var game;

var boidsAmount = 5;
var boids = [];
var target;

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(){
          game.load.image("boid", "boid.png");
          game.load.image("target", "target.png");     
     },
     create: function(){
          target = game.add.sprite(game.width / 2, game.height / 2, "target");
          target.anchor.set(0.5);
          for(var i = 0; i < boidsAmount; i++){
               var randomPoint = new Phaser.Point(game.rnd.between(0, game.width - 1), game.rnd.between(0, game.height - 1));
               boids[i] = game.add.sprite(randomPoint.x, randomPoint.y, "boid")
               boids[i].anchor.set(0.5);
               boids[i].speed = game.rnd.between(50, 150);
               boids[i].force = game.rnd.between(5, 25);
               game.physics.enable(boids[i], Phaser.Physics.ARCADE);
               boids[i].body.allowRotation = false;    
          }
     },
     update: function(){
          for(var i = 0; i < boidsAmount; i++){
               // direction vector is the straight direction from the boid to the target
               var direction = new Phaser.Point(target.x, target.y);
               // now we subtract the current boid position
               direction.subtract(boids[i].x, boids[i].y);
               // then we normalize it. A normalized vector has its length is 1, but it retains the same direction
               direction.normalize();
               // time to set magnitude (length) to boid speed
               direction.setMagnitude(boids[i].speed);
               // now we subtract the current boid velocity
               direction.subtract(boids[i].body.velocity.x, boids[i].body.velocity.y);
               // normalizing again
               direction.normalize();
               // finally we set the magnitude to boid force, which should be WAY lower than its velocity
               direction.setMagnitude(boids[i].force); 
               // Now we add boid direction to current boid velocity
               boids[i].body.velocity.add(direction.x, direction.y);
               // we normalize the velocity
               boids[i].body.velocity.normalize();
               // we set the magnitue to boid speed
               boids[i].body.velocity.setMagnitude(boids[i].speed);
               boids[i].angle = 180 + Phaser.Math.radToDeg(Phaser.Point.angle(boids[i].position, new Phaser.Point(boids[i].x + boids[i].body.velocity.x, boids[i].y + boids[i].body.velocity.y)));
               if(boids[i].position.distance(target.position) < 2){
                    target.x = game.rnd.between(10, game.width - 10);
                    target.y = game.rnd.between(10, game.height - 10);
               }
          }                    
     }     
}
This was just another demonstration of what you can do with boids. More will come, 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

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