private Vector3 Alignment(AgentBoid boid) { // Set velocity to zero. Vector3 alignment = Vector3.zero; int iterator = 0; for (int i = 0; i < flockSize; i++) { // Returns the distance between a and b. // Use this to find the distance between a boid and it's neighbour. float distance = Vector3.Distance(boids[i].transform.localPosition, boid.transform.localPosition); // If the distance between the two is greater than zero and less than the radius // defined in the AgentBoid script, then: if (distance > 0 && distance < boid.neighbourRad) { // Set the velocity. alignment += boids[i].boidRB.velocity; iterator++; } } // Return the alignment. Do not forget to normalize this! if (iterator > 0) { return((alignment / (flockSize - 1)).normalized); } else { return(Vector3.zero); } }
private Vector3 Separation(AgentBoid boid) { Vector3 separation = Vector3.zero; int iterator = 0; for (int i = 0; i < flockSize; i++) { // Returns the distance between a and b. // Use this to find the distance between a boid and it's neighbour. float distance = Vector3.Distance(boids[i].transform.localPosition, boid.transform.localPosition); if (distance > 0 && distance < boid.separationBound) { separation -= (boids[i].transform.localPosition - boid.transform.localPosition).normalized / distance; iterator++; } } // Return the separation vector. Do not forget to normalize this! if (iterator > 0) { return((separation / (flockSize - 1)).normalized); } else { return(Vector3.zero); } }
private Vector3 Cohesion(AgentBoid boid) { Vector3 cohesion = Vector3.zero; int iterator = 0; for (int i = 0; i < flockSize; i++) { // Returns the distance between a and b. // Use this to find the distance between a boid and it's neighbour. float distance = Vector3.Distance(boids[i].transform.localPosition, boid.transform.localPosition); if (distance > 0 && distance < boid.neighbourRad) { // Set the velocity. cohesion += boids[i].transform.localPosition; iterator++; } } // Return the cohesion vector. Do not forget to normalize this! if (iterator > 0) { return(((cohesion / (flockSize - 1)) - boid.transform.localPosition).normalized); } else { return(Vector3.zero); } }
private void FixedUpdate() { for (int i = 0; i < flockSize; i++) { // Select an individual boid. AgentBoid boid = boids[i]; // If the boid is not equal to null and the rigidbody is not equal to null: if (boid != null && boid.boidRB != null) { // Set the rules of the Reynolds algorithm by accessing the corresponding functions. Vector3 parsedAlignment = Alignment(boid) * alignmentWeight * Time.deltaTime; Vector3 parsedCohesion = Cohesion(boid) * cohesionWeight * Time.deltaTime; Vector3 parsedSeparation = Separation(boid) * separationWeight * Time.deltaTime; // Where the magic happens. Sum the vectors together. boid.boidRB.velocity += (parsedAlignment + parsedCohesion + parsedSeparation); } } }