Performance: Enemy patrol and chase patterns
This concept affects frame rate and responsiveness during gameplay by controlling how often enemy AI updates and moves.
void Update() {
if (Vector3.Distance(transform.position, player.position) < chaseRange) {
Vector3 direction = player.position - transform.position;
transform.position += direction.normalized * speed * Time.deltaTime;
} else {
Patrol();
}
}
void Patrol() {
// Move between waypoints with less frequent updates
}void Update() {
Vector3 direction = player.position - transform.position;
transform.position += direction.normalized * speed * Time.deltaTime;
// No checks, runs every frame
}| Pattern | CPU Usage | Update Frequency | Frame Impact | Verdict |
|---|---|---|---|---|
| Unconditional chase every frame | High | Every frame | Causes frame drops | [X] Bad |
| Conditional chase with distance check | Low to Medium | Only when player near | Smooth frame rate | [OK] Good |
if (Vector3.Distance(transform.position, player.position) < chaseDistance) {
Debug.Log("Chasing player");
} else {
Debug.Log("Patrolling");
}void Patrol() {
int currentPoint = 0;
transform.position = Vector3.MoveTowards(transform.position, patrolPoints[currentPoint].position, speed * Time.deltaTime);
if (transform.position == patrolPoints[currentPoint].position) {
currentPoint++;
if (currentPoint >= patrolPoints.Length) {
currentPoint = 0;
}
}
}Pass the test and this pattern moves unknown