Unity 4.x Game AI Programming by Aung Sithu Kyaw

Unity 4.x Game AI Programming by Aung Sithu Kyaw

Author:Aung Sithu Kyaw [Kyaw, Aung Sithu & Peters, Clifford & Swe, Thet Naing]
Language: eng
Format: epub
Published: 2014-05-04T04:00:00+00:00


We set the parent of the object of our boid as origin, meaning that this will be the controller object to follow generally. Then, we grab all the other boids in the group and store them in our own variables for later references.

The StartCoroutine method starts the UpdateRandom() method as a coroutine:

IEnumerator UpdateRandom() { while (true) { randomPush = Random.insideUnitSphere * randomForce; yield return new WaitForSeconds(randomFreq + Random.Range(-randomFreq / 2.0f, randomFreq / 2.0f)); } }

The UpdateRandom() method updates the randomPush value throughout the game with an interval based on randomFreq. Random.insideUnitSphere returns a Vector3 object with random x, y, and z values within a sphere with a radius of the randomForce value. Then, we wait for a certain random amount of time before resuming the while(true) loop to update the randomPush value again.

Now, here's our boid behavior's Update() method that helps our boid entity comply with the three rules of the flocking algorithm:

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 position 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 value if the magnitude, the length of the //vector, is less than 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; UnityFlock otherSealgull = otherFlocks[i]; //we normalize the otherSealgull velocity vector to get //the direction of movement, then we set a new velocity avgVelocity += otherSealgull.normalizedVelocity * f * followVelocity; } } }



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.