There are times when the number of waypoints must be reduced at a certain point during the game or just for memory constraints. In this recipe, we will learn a technique called condensation that helps us deal with this problem, forcing the waypoints to compete with each other given their assigned value.
In this recipe, we will deal with static member functions. It is important that we understand the use and value of static functions.
We will create the Waypoint
class and add the functions for condensing the set of waypoints.
Waypoint
class, deriving not only from MonoBehaviour
, but also from the IComparer
interface:using UnityEngine; using System.Collections; using System.Collections.Generic; public class Waypoint : MonoBehaviour, IComparer { public float value; public List<Waypoint> neighbours; }
Compare
function from the aforementioned interface:public int Compare(object a, object b) { Waypoint wa = (Waypoint)a; Waypoint wb = (Waypoint)b; if (wa.value == wb.value) return 0; if (wa.value < wb.value) return -1; return 1; }
public static bool CanMove(Waypoint a, Waypoint b) { // implement your own behaviour for // deciding whether an agent can move // easily between two waypoints return true; }
public static void CondenseWaypoints(List<Waypoint> waypoints, float distanceWeight) { // next steps }
distanceWeight *= distanceWeight; waypoints.Sort(); waypoints.Reverse(); List<Waypoint> neighbours;
foreach (Waypoint current in waypoints) { // next steps }
neighbours = new List<Waypoint>(current.neighbours); neighbours.Sort(); foreach (Waypoint target in neighbours) { if (target.value > current.value) break; if (!CanMove(current, target)) continue; // next steps }
Vector3 deltaPos = current.transform.position; deltaPos -= target.transform.position; deltaPos = Vector3.Cross(deltaPos, deltaPos); deltaPos *= distanceWeight;
float deltaVal = current.value - target.value; deltaVal *= deltaVal; if (deltaVal < distanceWeight) { neighbours.Remove(target); waypoints.Remove(target); }
The waypoints are ordered according to their relevance (such as height to be used as a sniping or advantage location) and then their neighbors are checked to see which ones are going to be dismissed from the condensation. Naturally, the less valuable waypoints are kept to the end of the computation cycle. In the next recipe, we will learn how to analyze waypoints.