Skip to content

Instantly share code, notes, and snippets.

@sidonath
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sidonath/36607e292c0964d66da0 to your computer and use it in GitHub Desktop.
Save sidonath/36607e292c0964d66da0 to your computer and use it in GitHub Desktop.
// is the other bird within a certain distance
def within(dist: Float) = { other: Boid =>
val d = loc distance other.loc
d > 0 && d < dist
}
// Sum, and divide by size
def avg(l: List[Vector]) = (l :\ new Vector)(_ + _) / (l.size max 1)
// Separation
// Method checks for nearby boids and steers away
def separate (boids: List[Boid]) =
avg(boids.filter(within(25.0)).map { other =>
(loc - other.loc).normalized / (loc distance other.loc)
})
// Separation
// Method checks for nearby boids and steers away
Vector3D separate (ArrayList boids) {
float desiredseparation = 25.0f;
Vector3D sum = new Vector3D(0,0,0);
int count = 0;
// For every boid in the system, check if it's too close
for (int i = 0 ; i < boids.size(); i++) {
Boid other = (Boid) boids.get(i);
float d = loc.distance(loc,other.loc);
// If the distance is greater than 0 and less than an arbitrary amount
// (0 when you are yourself)
if ((d > 0) && (d < desiredseparation)) {
// Calculate vector pointing away from neighbor
Vector3D diff = loc.sub(loc,other.loc);
diff.normalize();
diff.div(d); // Weight by distance
sum.add(diff);
count++; // Keep track of how many
}
}
// Average -- divide by how many
if (count > 0) {
sum.div((float)count);
}
return sum;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment