- Home /
Boids for 2D
Hi I used the unity 4.x game AI programming to make some boids the only problem is the book makes them for 3D while I am trying to do them in 2D, they work fine only problem is when they turn they rotate and disappear from view for bit until they end up flat again since they are only sprites.
Here's my code- using UnityEngine; using System.Collections;
public class Flock : MonoBehaviour {
public float minSpeed = 20.0f;
public float turnSpeed = 20.0f;
public float randomFreq = 20.0f;
public float randomForce = 20.0f;
//aligment varibles
public float toOriginForce = 50.0f;
public float toOrginRange = 100.0f;
public float gravity = 2.0f;
//speration variables
public float avoidanceRadius = 50.0f;
public float avoidanceForce = 20.0f;
//cohesion varibles
public float followVelocity = 4.0f;
public float followRadius = 40.0f;
//Movment of boids variables
private Transform origin;
private Vector3 velocity;
private Vector3 normalizedVelocity;
private Vector3 randomPush;
private Vector3 originPush;
private Transform[] objects;
private Flock[] otherFlocks;
private Transform transformComponent;
// Use this for initialization
void Start () {
randomFreq = 1.0f;
//Assign the parent as origin;
origin = transform.parent;
//Flock transform
transformComponent = transform;
//Temporary components
Component[] tempFlocks = null;
//Get all the flock components fromthe parent
//Transform in the group
if (transform.parent) {
tempFlocks = transform.parent.GetComponentsInChildren <Flock> ();
}
//Assign and Store allthe flock objects in this group
objects = new Transform[tempFlocks.Length];
otherFlocks = new Flock[tempFlocks.Length];
for (int i = 0; i < tempFlocks.Length; i++) {
objects [i] = tempFlocks [i].transform;
otherFlocks [i] = (Flock)tempFlocks [i];
//Null parent as the flock leader will be
// FlockController object
transform.parent = null;
//Calculate random push depends on the random frequency provided
StartCoroutine (UpdateRandom ());
}
}
IEnumerator UpdateRandom() {
while (true) {
randomPush = Random.insideUnitSphere * randomForce;
yield return new WaitForSeconds (randomFreq + Random.Range (-randomFreq / 2.0f, randomFreq / 20.0f));
}
}
// Update is called once per frame
void Update () {
//Internal variables
float speed = velocity.magnitude;
Vector3 avgVelocity = Vector3.zero;
Vector3 avgPosition = Vector3.zero;
float count = 0;
float f = 0.0f;
float d = 0.0f;
Vector3 myPosition = transformComponent.position;
Vector3 forceV;
Vector3 toAvg;
Vector3 wantedVel;
for (int i = 0; i <objects.Length;i++){
Transform transform = objects[i];
if (transform != transformComponent) {
Vector3 otherPosition = transform.position;
// Average Poition to calculate cohesion
avgPosition += otherPosition;
count++;
//Directional Vector from other flock to this flock
forceV = myPosition - otherPosition;
//Magnitude of that directional vector(length)
d = forceV.magnitude;
//Add push vaule if the magnitude, the ; length of the vector, is less then followRadius to the leader
if (d < followRadius) {
//calculate the velocity, the speed of the object, based on the avoidance distance between flocks if the current magnitude is less than the specified avoidance radius
if (d < avoidanceRadius){
f = 1.0f - (d / avoidanceRadius);
if (d > 0) avgVelocity += (forceV / d) * f * avoidanceForce;
}
//just keep the current distance with the leader
f = d / followRadius;
Flock otherBoids = otherFlocks[i];
//We normalize the otherBoids velocity vector to get the direction of the movement, then we set a new velocity
avgVelocity += otherBoids.normalizedVelocity * f * followVelocity;
}
}
}
if (count > 0) {
//Calculate the aerage flock velocity(Alignment)
avgVelocity /= count;
//Calculate Cwnter value of the flock(Cohesion)
toAvg = (avgPosition / count) - myPosition;
}
else {
toAvg = Vector3.zero;
}
//Directional Vector to the leader
forceV = origin.position - myPosition;
d = forceV.magnitude;
f = d / toOrginRange;
//Calculate the velocity of the flock to the leader
if ( d > 0) //if this void is not at the center of the flock
originPush = (forceV / d) * f * toOriginForce;
if (speed < minSpeed && speed > 0) {
velocity = (velocity / speed) * minSpeed;
}
wantedVel = velocity;
//Calculate final velocity
wantedVel -= wantedVel * Time.deltaTime;
wantedVel += randomPush * Time.deltaTime;
wantedVel += originPush * Time.deltaTime;
wantedVel += avgVelocity * Time.deltaTime;
wantedVel += toAvg.normalized * gravity * Time.deltaTime;
//Final Velocity to rotate the flock into
velocity = Vector3.RotateTowards(velocity, wantedVel, turnSpeed * Time.deltaTime, 100.00f);
transformComponent.rotation = Quaternion.LookRotation(velocity);
//Move the flock based on the calculated Velocity
transformComponent.Translate(velocity * Time.deltaTime, Space.World);
//nomralise the velocity
normalizedVelocity = velocity.normalized;
}
}
I also a have flock controller, but I didn't think it was needed to fix this if it is then tell me and I shell put it up. I tried changing it, but doesn't work since Quaternion has to take all four axis x,y,z and w. How can I change this code so my sprites won't rotate to the point they aren't visible anymore. If you answer can you specify what to do and what I need to get rid of or change and where to put it in my code please.
Your answer
Follow this Question
Related Questions
How can I multiply the rotation of a mirrored object? 1 Answer
How to instantiate on custom rotation? 1 Answer
Ball Rolling Animation Not Working Properly 0 Answers
Rotating an object towards target on a single axis 2 Answers
Basic AI Locked Axis 1 Answer