In this lesson, you will learn how to boost simulation performance by dynamically adjusting the frequency of AI decision-making based on the distance between the agent and the player.
The Strategy: Dynamic Throttling
In a large-scale simulation, running expensive AI logic (like GOAP planning or utility-based evaluations) every single frame for hundreds of agents is a recipe for performance degradation. Since NPCs far away from the player are less noticeable, we can "throttle" their update frequency. By moving from a "constant update" model to a "distance-based frequency" model, we drastically reduce the CPU load without sacrificing visual fidelity in the immediate vicinity.
Implementation Logic
We divide the world into concentric distance zones. For example:
- Near (0–20m): Update every frame (High fidelity).
- Medium (20–50m): Update every 10 frames (Medium fidelity).
- Far (50m+): Update every 30 frames (Low fidelity).
We achieve this by checking the distance from the Camera.main.transform and maintaining a frameCounter to determine if it is the agent's "turn" to compute its state.
private int frameCounter = 0;
void Update() {
float distance = Vector3.Distance(transform.position, Camera.main.transform.position);
int updateInterval = CalculateInterval(distance);
if (frameCounter >= updateInterval) {
PerformAgentLogic(); // e.g., Plan GOAP or update Utility scores
frameCounter = 0;
}
frameCounter++;
}
int CalculateInterval(float dist) {
if (dist < 20f) return 1;
if (dist < 50f) return 10;
return 30;
}
Balancing the Trade-off
When an agent updates less frequently, its behavior may appear "stiff." To compensate, ensure that your state machines or utility selectors use interpolation or simple movement logic that persists between updates. While the "decision" logic (what to do next) is throttled, the low-level movement or animation should remain fluid to keep the illusion of life intact. By scaling these updates, you free up CPU budget to support much larger, more complex agent populations.
Key Takeaway: By coupling AI update frequency to distance from the observer, you prioritize processing power for agents the player actually sees, allowing for massive, performant crowd simulations.