Flocking combines three steering behaviors: alignment, cohesion, and separation.

I adapted this from a p5.js demo. There’s also a good series, Understanding Steering Behaviors, in ActionScript.

I used Vector2 a lot. Here is a basic steering function:

function steer(body, desiredVelocity, steeringForceResult) {
    return steeringForceResult

and a seek function:

function seek(body, target, steeringForceResult) {
  const desiredVelocity = target.clone().subtract(body.center);

  return steer(body, desiredVelocity, steeringForceResult);

Steering forces are summed into acceleration, and then Arcade Physics produces the movement.

I searched the spatial tree to select nearby vehicles:

const alignBodies = this.scene.physics.overlapCirc(x, y, alignRange);

This is a lot more efficient than checking every distance pair.

You can adjust the simulation parameters and display the steering vectors.


I love this type of stuff! Thank you for posting!
It’s interesting how you use the built-in spatial tree to make it efficient.

1 Like