Created
April 5, 2014 03:52
-
-
Save tmcnab/9987277 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Assets.RED.Scripts.Behaviors | |
{ | |
using System; | |
using UnityEngine; | |
public abstract class BoidBase : MonoBehaviour | |
{ | |
public float DetectionRadius; | |
public float TurningSpeed; | |
public float Velocity; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Assets.RED.Scripts.Behaviors | |
{ | |
using System; | |
using System.Linq; | |
using UnityEngine; | |
public class FlockCenter : BoidBase | |
{ | |
private void FixedUpdate() | |
{ | |
// Find all the objects within the boid's detection radius. | |
var scanHits = Physics.OverlapSphere(base.transform.position, base.DetectionRadius); | |
int count = 0; | |
Vector3 sum = new Vector3 (); | |
// Iterate over all objects and if they're of the same type the move towards center of the flock | |
foreach (var hit in scanHits.Where(h => h.collider.tag == "Enemy")) | |
{ | |
sum = sum + hit.collider.rigidbody.position; | |
count++; | |
} | |
var center = sum / count; | |
var desiredPosition = center.normalized; | |
base.transform.position = Vector3.MoveTowards (base.transform.position, desiredPosition, Time.deltaTime); | |
base.rigidbody.velocity = base.transform.TransformDirection(Vector3.forward * base.Velocity); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment