Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Agent : MonoBehaviour
- {
- public float alignmentWeight = 1.0f;
- public float cohesionWeight = 1.0f;
- public float seperationWeight = 1.0f;
- public float speed = 3.0f;
- public Vector3 Direction { get; private set; }
- private void Start()
- {
- Direction = UnityEngine.Random.insideUnitSphere;
- FlocksManager.AddAgent(this);
- }
- private void Update()
- {
- List<Agent> _neighbors = FlocksManager.GetNeighbors(this);
- //Calculate my final direction
- Direction = Alignment(ref _neighbors) * alignmentWeight + Separation(ref _neighbors) * seperationWeight + Cohesion(ref _neighbors) * cohesionWeight;
- //Make it a radius of 1
- Direction.Normalize();
- transform.position += Direction * speed * Time.deltaTime;
- }
- Vector3 Alignment(ref List<Agent> _neighbors)
- {
- Vector3 alignment = Vector3.zero;
- for(int i = 0; i < _neighbors.Count; ++i)
- {
- alignment += _neighbors[i].Direction;
- }
- return alignment / (float)_neighbors.Count;
- }
- Vector3 Cohesion(ref List<Agent> _neighbors)
- {
- Vector3 cohesion = Vector3.zero;
- for (int i = 0; i < _neighbors.Count; ++i)
- {
- cohesion += _neighbors[i].transform.position;
- }
- return cohesion / (float)_neighbors.Count;
- }
- Vector3 Separation(ref List<Agent> _neighbors)
- {
- Vector3 cohesion = Vector3.zero;
- for (int i = 0; i < _neighbors.Count; ++i)
- {
- cohesion -= _neighbors[i].transform.position;
- }
- return cohesion / (float)_neighbors.Count;
- }
- }
- static class FlocksManager
- {
- static float neighborRadius = 3.0f;
- static List<Agent> agents = new List<Agent>();
- public static void AddAgent(Agent _agent)
- {
- agents.Add(_agent);
- }
- public static void RemoveAgent(Agent _agent)
- {
- agents.Remove(_agent);
- }
- public static List<Agent> GetNeighbors(Agent _agent)
- {
- List<Agent> neighbors = new List<Agent>();
- for(int i = 0; i < agents.Count; ++i)
- {
- if(Vector3.SqrMagnitude(agents[i].transform.position - _agent.transform.position) < neighborRadius * neighborRadius)
- {
- neighbors.Add(agents[i]);
- }
- }
- return neighbors;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement