using UnityEngine; [RequireComponent(typeof(NanoBrain))] public class Boid : MonoBehaviour { public static int BoundaryType = 1; public static int BoidType = 2; public SwarmControl sc; public Vector3 velocity = Vector3.zero; public Vector3 acceleration = Vector3.zero; private Bounds innerBounds; public NanoBrain neuroidNet; public Perception perception; public Nucleus behaviour; public Neuroid totalForce; public int id; void Awake() { neuroidNet = GetComponent(); this.id = this.GetInstanceID(); sc = FindFirstObjectByType(); innerBounds = new(sc.transform.position, sc.spaceSize - 2 * sc.boundaryWidth); perception = new Perception(neuroidNet); //behaviour = new Roaming(neuroidNet, perception, sc); behaviour = new Swarming(neuroidNet, perception, sc); totalForce = new(neuroidNet, "Total"); behaviour.AddReceiver(totalForce); } void Update() { Collider[] results = Physics.OverlapSphere(this.transform.position, sc.perceptionDistance); foreach (Collider c in results) { if (c as CapsuleCollider != null) { Boid neighbour = c.GetComponentInParent(); if (neighbour == null || neighbour == this) continue; Vector3 localPosition = this.transform.InverseTransformPoint(neighbour.transform.position); //Debug.DrawRay(this.transform.position, this.transform.TransformDirection(localPosition), Color.magenta); int thingId = neighbour.GetInstanceID(); perception.ProcessStimulus(thingId, BoidType, localPosition, neighbour.gameObject.name); } } if (!innerBounds.Contains(this.transform.position)) { Vector3 point = this.transform.position; Vector3 pointOnBounds = innerBounds.ClosestPoint(point); Vector3 desiredWorldSpace = (pointOnBounds - point).normalized * sc.speed; Vector3 desiredLocalSpace = -this.transform.InverseTransformPoint(desiredWorldSpace); perception.ProcessStimulus(777, BoundaryType, desiredLocalSpace, "Boundary"); } Vector3 worldForce = this.transform.TransformDirection(behaviour.outputValue); this.velocity = (1 - sc.inertia) * (worldForce * Time.deltaTime) + sc.inertia * velocity; if (this.velocity.magnitude > 0) this.velocity = this.velocity.normalized * sc.speed; else this.velocity = this.transform.forward * sc.speed; Debug.DrawRay(this.transform.position, this.velocity, Color.blue); this.transform.position += this.velocity * Time.deltaTime; if (this.velocity != Vector3.zero) { Quaternion targetRotation = Quaternion.LookRotation(this.velocity); transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 2f); // Adjust the speed of rotation } neuroidNet.UpdateNeurons(); } }