void move() { if (translate) { transform.Translate(transform.right * Time.deltaTime * boidSpeed, Space.World); } // the direction the boid is currently travelling in Vector2 path = transform.right; Collider2D[] colliders = Physics2D.OverlapCircleAll(transform.position, 0.2f); Collider2D[] nearby = Physics2D.OverlapCircleAll(transform.position, 1.0f); if (colliders.Length == 0) { return; } Vector3 newHeading = transform.right; if (boidManager.separation) { newHeading += separation(nearby); } if (boidManager.alignment) { newHeading += alignment(colliders); } else { if (cluster != null) { cluster = null; } } if (boidManager.cohesion) { newHeading += cohesion(); } Vector3 dir = newHeading / newHeading.magnitude; dir.z = 0; dir.Normalize(); if (boidManager.travelDirection) { Debug.DrawRay(transform.position, dir, Color.white); } transform.right = dir; if (boidManager.wrap) { wrapScreen(); } }
public void merge(BoidCluster b) { if (boids.Count + b.boids.Count > parentBoid.boidManager.maximumClusterSize) { return; } float weight = b.size() / (size() + b.size()); Vector3 newDirection = Vector3.Lerp(clusterDirection, b.clusterDirection, weight); int old = boids.Count; boids = boids.Union(b.boids).ToList <Boid>(); clusterDirection = newDirection; foreach (Boid boid in b.boids) { boid.cluster = this; } }
Vector3 alignment(Collider2D[] colliders) { Vector3 vectorToAdd = Vector3.zero; foreach (Collider2D collider in colliders) { if (collider.gameObject != gameObject && canCreateCluster) { Boid b = collider.gameObject.GetComponent <Boid>(); if (b.cluster == null && cluster == null) { BoidCluster cluster = new BoidCluster(); cluster.add(GetComponent <Boid>()); cluster.add(b); } else if (cluster == null && !b.cluster.contains(GetComponent <Boid>())) { b.cluster.add(GetComponent <Boid>()); } else if (b.cluster == null && !cluster.contains(b)) { cluster.add(b); } else if (b.cluster != cluster) { if (cluster.size() >= b.cluster.size()) { cluster.add(b); } else { b.cluster.add(GetComponent <Boid>()); } } } } if (cluster != null) { clusterDirection = cluster.clusterDirection; Vector3 rotate = Vector3.RotateTowards(transform.right, clusterDirection, 10.0f * Time.deltaTime, 0.0f); rotate.Normalize(); vectorToAdd += rotate; } return(vectorToAdd); }