Processing Forum
import toxi.geom.*;
ArrayList population;
void setup(){
size(500,500);
smooth();
population = new ArrayList();
for(int i = 0; i < 100; i++){
Vec3D p = new Vec3D(random(0,width),random(0,height),0);
Vec3D v = new Vec3D(2,-1,0);
agent a = new agent(p, v, random(3,4), random(0.1,0.3));
population.add(a);
}
}
void draw(){
background(0);
for(int i = 0; i < population.size(); i++){
agent a = (agent) population.get(i);
a.update();
a.render();
}
}
Vec3D alignment(ArrayList pop, float range){
Vec3D sum = new Vec3D();
int count = 0;
// loop through all the agents in pop arraylist
for(int i = 0; i < pop.size(); i++){
// get one agent out of the arraylist - call it a
agent a = (agent) pop.get(i);
// calculate distance to agent a
float d = pos.distanceTo(a.pos);
// is agent inside range of vis: if d < range
if( (d < range) && (a != this) ){
// add agent a vel to sum and add 1 to count
sum.addSelf(a.vel);
count++; // count = count + 1
}
}
// find the average vel: sum/count: sum * 1/count
if(count > 0){
sum.scaleSelf(1/(float)count);
// limit average vel
sum.limit(maxForce);
}
// return the limited average vel
return sum;
}