Flocking algorithm in VastPark
Many months ago during May of 09, after meeting Ian Hughes at FCVW, I came across an interesting post on his blog discussing an implementation of the flocking algorithm in Unity.
I’d not heard of the term flocking or boids, so proceeded to get stuck into some research, which lead me to Conrad Parker’s page on Boids Pseudocode as well as many others who had implemented the algorithm, I figured it would be a fun little plugin to write for VastPark so gave it a try.
Implementing the algorithm
Thinking about what was required, I came up with the following as the plan for the plugin:
- Any IPositionalElement (Model, Primitive, Sound, Camera, Light, etc) would be supported
- Implement Rule 1 – “Boids try to fly towards the centre of mass of neighbouring boids”
- Implement Rule 2 – “Boids try to keep a small distance away from other objects (including other boids)”
- Implement Rule 3 – “Boids try to match velocity with near boids”
- For bonus points I’d implement “Tendency towards a particular place”, “Limiting the speed”, “Bounding the position”, “Perching” and “Scattering the flock”
In terms of the plugin this translates into these properties:
- SmallDistance
- MaxVelocity
- MinVelocity
- EnableBounds
- MaxBounds
- MinBounds
- EnablePerching
- MinPerchTime
- MaxPerchTime
- PerceivedCentre (get only)
The following callbacks:
- ElementPerched
- ElementLeftPerch
The following methods:
- SetPointOfInterest
- AddPlaceToAvoid
- AddPerch
- Scatter
The class diagrams look like this:
How does it work?
Put quite simply, the plugin works like this:
- AddElement(ImmlElement element) creates a boid instance for the positional element passed
- The plugin Update method (called once each update by the VastPark framework) proceeds to calculate the rules, one at a time for each boid to work out the new velocity and position for the element it represents
- Scatter requests made during runtime are dealt with during the next update
Downloads
Here is some sample IMML and the source code to the plugin, enjoy! Let me know if you decide to implement any of the other rules or do something cool with it 🙂
Sample IMML: flocking.imml
Source code to plugin: Plugin.Flocking.zip
Note: The source code will probably complain about some missing references. Install the Player from www.vastpark.com and link against the relevant binaries included with it.