# Flocking as in NatureOfCode

Question on flocking. In many examples (and also on The Nature of Code) there’s something like:

`````` if (count > 0) {
sum.div(count);
sum.normalize();
sum.mult(maxspeed);
PVector steer = PVector.sub(sum,velocity);
steer.limit(maxforce);
return steer;
}
``````

In the ‘align’ as well as ‘separate’ code examples. Now the question: Why divide the vector by a scalar before normalizing it? Dividing only changes magnitude, and normalizing only changes the magnitude and always has the same outcome (magnitude wise) regardless of any previous magnitude. So, why the division before the normalization? What am I missing here?

Kind regards,
Manno

Hi manno,

Haven’t looked in detail but you are right, you could get rid of `sum.div(count)` and the result would be the same.

Maybe the initial idea was to take an average value and then it changed to be the maxspeed all the time But as is, you can for sure get rid of the division line and it wouldn’t change anything.

I guess it’s just a mistake; I mean perhaps a residue from something else. It may be helpful to make a pull request or send feedback to Dan. He sometimes makes these mistakes, and we all love him

Out of curiosity I changed the value to see what can potentially go wrong with this line. With this large value, sometimes boids are stuck depending on their position.

Thanks @jb4x and @micuat .
tbh, I had not even thought about the repo and communicating through that. Might do that, thanks

Very large numbers as the denominator are pretty rare I suppose. Having that size of ‘neighbourhood’ would not benefit the frame rate at least .

Kind regards,
Manno

1 Like

From my understanding the flocking algorithm checks and takes the average velocity of a boid and the boids in its vicinity, hence the div(count) count being the neighbour of boids withina certain radius.

Partially true @paulgoux. Flocking deals with getting an average velocity (to align your own to), an average position (to move towards to for cohesion) and an average ‘evasion vector’ (to separate).
However, in calculating all this, after summing vectors, division is useless if you are going to normalize the vector immediately after. It is setting the length to some calculated value (division) after which you set it to be of length one (normalize), and nothing happens in between.

Vector math wise, you only need to divide by the ‘neighbour count’ for the cohesion. There you need an average position which you want to steer towards using seek. With alignment and separation the total vector is set to a certain magnitude (independent of the amount of neighbours that contributed to the total) to limit its ‘force’.