Skip to content

Instantly share code, notes, and snippets.

@tmcnab
Created April 5, 2014 03:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmcnab/9987277 to your computer and use it in GitHub Desktop.
Save tmcnab/9987277 to your computer and use it in GitHub Desktop.
namespace Assets.RED.Scripts.Behaviors
{
using System;
using UnityEngine;
public abstract class BoidBase : MonoBehaviour
{
public float DetectionRadius;
public float TurningSpeed;
public float Velocity;
}
}
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