Last active
August 29, 2015 14:04
-
-
Save sidonath/36607e292c0964d66da0 to your computer and use it in GitHub Desktop.
Impretive vs FP style (http://technically.us/code/x/flocking-with-spde/)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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) | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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