Monday, January 21, 2013

The Three Simple Rules of Flocking Behaviors: Alignment, Cohesion, and Separation

In the natural world, organisms exhibit certain behaviors when traveling in groups. This phenomenon, also known as flocking, occurs at both microscopic scales (bacteria) and macroscopic scales (fish). Using computers, these patterns can be simulated by creating simple rules and combining them. This is known as emergent behavior, and can be used in games to simulate chaotic or life-like group movement. Note: Although this tutorial is written using Flash and AS3, you should be able to use the same techniques and concepts in almost any game development environment.

Introduction

In this tutorial, I will cover the three main rules used to simulate flocking and explain how to implement each one.  Before we begin, here’s some terminology I’ll be using:
  • Agent: A single entity or character.
  • Velocity vector: An agent’s current velocity.
  • Neighborhood: A certain area around the agent, used to look for other agents.
  • Resultant: The vector obtained from the calculations of the rule.
This demo shows the effects of the three flocking rules which I’ll explain in this tutorial: alignment, cohesion, and separation.
The full source code for this demo can be downloaded here, so this article will only highlight the most important aspects of the implementation. Feel free to download the source if you wish to learn more.

Alignment

Image adapted from Craig Reynolds’ article
Alignment is a behavior that causes a particular agent to line up with agents close by. First, we’ll make a function that takes an agent and returns a velocity vector.
public function computeAlignment(myAgent:Agent):Point
{
}
We’ll need two variables: one for storing the vector we’ll compute, and another for keeping track of the number of neighbors of the agent.
var v:Point = new Point();
var neighborCount = 0;
[...]
Read more: The Three Simple Rules of Flocking Behaviors: Alignment, Cohesion, and Separation

No comments:

Post a Comment