Flocking

by Sam Fereday

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/2.4.4/phaser.min.js"></script>
<div id="phaser-example"></div>
<div id="currentvelocity"></div>
<div id="currentWeights"></div>
<input id="aliweight" value="0.3" />
<input id="cohweight" value="0.5" />
<input id="sepweight" value="0.8" />
<p>
http://gamedevelopment.tutsplus.com/tutorials/the-three-simple-rules-of-flocking-behaviors-alignment-cohesion-and-separation--gamedev-3444
</p>

CSS

body {
  font: 75%/1.4em arial;
}

JavaScript

var game = new Phaser.Game(400, 400, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update });
var cv = document.getElementById("currentvelocity");
var cw = document.getElementById("currentWeights");

function preload() {

    game.load.image('mushroom','mushroom.png');

}

var effect;
var image;
var testSprite;
var mask = new Phaser.Rectangle();
var AGENT_SPEED = 36; // const
var MAX_VELOCITY = 100;
var agentArray = [];

// Constants
var alignmentWeight = 0.5;
var cohesionWeight = 0.5;
var separationweight = 1;

function update() {

		alignmentWeight = document.getElementById("aliweight").value;
    cohesionWeight = document.getElementById("cohweight").value;
    separationweight = document.getElementById("sepweight").value;
    
    cw.innerHTML = alignmentWeight + ":" + cohesionWeight + ":" + separationweight + "";

		// Clear the bitmap where we are drawing our lines
    this.bitmap.context.clearRect(0, 0, game.width, game.height);
    var self = this;

		agentArray.forEach(function(agent){
    
    		var alignment = calcalignment(agent);
        var cohesion = calccohesion(agent);
        var separation = calcseparation(agent);   

        agent.velocity.normalize(AGENT_SPEED);

				var thing = alignment.y * alignmentWeight + cohesion.y * cohesionWeight + separation.y * separationweight ;
        
        console.log(agent.sprite.body.velocity);
        agent.sprite.body.acceleration.x += alignment.x * alignmentWeight + cohesion.x * cohesionWeight + separation.x * separationweight;
        agent.sprite.body.acceleration.y += alignment.y * alignmentWeight + cohesion.y * cohesionWeight + separation.y * separationweight;
                
        //game.world.wrap(agent.sprite, 0, true);
        
        cv.innerHTML = "<p>Current Velocity:</p><p>" + agent.sprite.body.velocity.toString() + "</p>";
        
        // If you want a target, you'll need to do some more vector math.
        
        // Some debug
       ...