From 5b16c736ee07665e9a2e3926350a37350e10efd9 Mon Sep 17 00:00:00 2001 From: Xevion Date: Sat, 16 May 2020 13:05:48 -0500 Subject: [PATCH] update Boid class for new Monobehavior structure --- Assets/Boid.cs | 36 ++++++++++++++---------------------- 1 file changed, 14 insertions(+), 22 deletions(-) diff --git a/Assets/Boid.cs b/Assets/Boid.cs index 022e3ae..82c05bd 100644 --- a/Assets/Boid.cs +++ b/Assets/Boid.cs @@ -1,22 +1,13 @@ using System.Collections.Generic; using UnityEngine; -public class Boid { - private Vector2 _position; - private Vector2 _velocity; +// Boids are represented by a moving, rotating triangle. +// Boids should communicate with sibling Boids +public class Boid : MonoBehaviour { + public Vector2 velocity = Vector2.zero; - public Boid(Vector2 position, Vector2 velocity) { - _position = position; - _velocity = velocity; - } - - public void SetPosition(Vector2 position) { - _position = position; - } - - // Renders the Boid. If focused, the - void Render(bool focused = false) { - + void Start() { + velocity = Vector2.one; } // Returns the next position the Boid will be moving to @@ -29,23 +20,23 @@ public class Boid { Vector2 r2 = Rule2(flock) * magnitudes[1]; Vector2 r3 = Rule3(flock) * magnitudes[2]; - return _position + r1 + r2 + r3; + return transform.position + (Vector3) (r1 + r2 + r3); } // Cohesion: Steer towards center of mass of flock Vector2 Rule1(List flock) { Vector2 center = Vector2.zero; foreach (Boid boid in flock) - center += boid._position; + center += (Vector2) boid.transform.position; center /= flock.Count; - return (center - _position) / 100; + return (center - (Vector2) transform.position) / 100; } // Separation: Steer to avoid other Boids within flock Vector2 Rule2(List flock) { Vector2 c = Vector2.zero; foreach (Boid boid in flock) { - Vector2 diff = boid._position - _position; + Vector2 diff = boid.transform.position - transform.position; if (diff.magnitude < 5) c -= diff; } @@ -56,15 +47,16 @@ public class Boid { Vector3 Rule3(List flock) { Vector2 perceived = Vector2.zero; foreach (Boid boid in flock) - perceived += boid._velocity; + perceived += boid.velocity; perceived /= flock.Count; - return (perceived - _velocity) / 8; + return (perceived - velocity) / 8; } + // Returns a list of boids within a certain radius of the Boid, representing it's local 'flock' List GetFlock(List boids, float radius) { List flock = new List(); foreach(Boid boid in boids) - if(boid != this && Vector2.Distance(_position, boid._position) <= radius) + if(boid != this && Vector2.Distance(transform.position, boid.transform.position) <= radius) flock.Add(boid); return flock; }