I want to change the Flocking

I want to change the weight of cohesion only for the agent added by clicking in the sample code of Flocking. How do I change the code?

1 Like

The boid code uses an enhanced for loop,

So there are two methods to achieve what you are looking for, which is either to make use of a traditional for loop which would then produce an index for you which would allow you to keep track of the last boid added

//enhanced for loop doesn't use`int i=0 ;i<.... `
for (Boid other : boids) {
      float d = PVector.dist(position, other.position);
      // 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
        PVector diff = PVector.sub(position, other.position);
        diff.normalize();
        diff.div(d);        // Weight by distance
        steer.add(diff);
        count++;            // Keep track of how many
      }
    }
    // Average -- divide by how many
    if (count > 0) {
      steer.div((float)count);
    }

Or add an index to the enhanced for loop keep track of the boids and then update your steering forces accordingly

int index = 0;
for(Element song : question) {
    System.out.println("Current index is: " + (index++));
}
1 Like

I’m not sure what part of the enhanced for loop has changed from the original one.
I want to change only the cohesion of the agents that are added by clicking on them, so that they blend in with the original swarm.

Do you mean you don’t know what parts to change in the enhanced for loop to make it a regular loop?

In this sample code, clicking on the screen will generate a new agent.
I want to change the cohesion of this agent only and observe the whole swarm.

In order to do that you first need to identify which boid you have added. Keeping track of them is key. Either using an index or another method.

Regular for loops provide the index for you. Enhanced for loops dont and therfore you need to ad the index.

When à boid is added, you need to find the index the boid is currently assigned to, evaluate its position, velocity and acceleration compare it to the local boids and steer towards it or align to it.

Please take some time to either read through the relevant chapters of the nature of code which explains all of this far better than I’m ever going to or check out some of Dan Shiffman’s videos on the topic on YouTube.

1 Like