# Context Steering, Patrol Paths & Telegraphed Enemy Encounters in Godot 4

> Typed GDScript 4 context steering, LevelData patrol-path following, line-of-sight perception with memory hysteresis, attack-token pacing, and telegraphed combat state machines.

- **Canonical page:** https://gamecrew.ai/techniques/godot/enemy-npc-ai-steering
- **Techniques hub:** https://gamecrew.ai/techniques
- **Engine:** Godot 4
- **Category:** ai
- **Tags:** `ai`, `enemy`, `npc`, `steering`, `patrol`, `telegraph`, `combat`, `attack-tokens`, `perception`
- **Verification:** Compile-verified pattern

## When to Use & Field Best Practices

Responsive 3D enemies and companions in Godot 4 combine **8-slot context steering** (`PhysicsDirectSpaceState3D.intersect_ray`), **`LevelData` patrol routes** (`level.json` `"paths"`), **explicit telegraph $\to$ active $\to$ recovery combat phases**, and an **attack-token coordinator** so crowds flank readably instead of stacking into a single capsule:
1. **Typed GDScript 4 Math**: Always use `clampf`, `maxf`, `minf`, `cos`, `sin`, `atan2`, and explicit types (`var score: float = ...`) so strict GDScript compilation passes with zero warnings.
2. **Patrol Routes in `level.json`**: Read waypoints from `LevelData.load_default().path("guard_loop")` rather than hardcoding magic coordinates in scripts.
3. **Telegraph Silhouettes & Recovery Windows**: Give every lunge or projectile a clear `0.4–0.65 s` windup before activating hitboxes, plus a `0.6 s` post-strike recovery window.

## Mathematical & Algorithmic Core

- **8-Slot Context Steering**: For unit directions $\hat{\mathbf{u}}_i = (\cos \frac{\tau i}{8}, 0, \sin \frac{\tau i}{8})$, compute interest $I_i = \max(0.05, \hat{\mathbf{u}}_i \cdot \hat{\mathbf{g}})$ and obstacle danger $D_i \in [0, 1]$ from short horizontal ray probes; sum $\sum \hat{\mathbf{u}}_i I_i (1 - D_i)$ across unblocked slots ($D_i \le 0.7$).
- **Orbit Flank Vector**: Combine radial spacing error $\mathrm{clamp}((d - r_{\text{pref}}) / r_{\text{pref}}, -1, 1)$ with tangent $(-\hat{r}_z, 0, \hat{r}_x)$ so enemies waiting for an attack token circle at `preferred_radius`.

## Engine Implementation

### Typed Context Steering, Token Pool & Enemy Brain (`Assets/Game/Scripts/gameplay/enemy_ai.gd`)

```gdscript
class_name EnemyAI
extends RefCounted


class TokenPool extends RefCounted:
	var max_tokens: int = 2
	var _holders: Dictionary = {}

	func try_acquire(actor_id: int) -> bool:
		if _holders.has(actor_id):
			return true
		if _holders.size() >= max_tokens:
			return false
		_holders[actor_id] = true
		return true

	func release(actor_id: int) -> void:
		_holders.erase(actor_id)

	func active_count() -> int:
		return _holders.size()


static func solve_context(
	space: PhysicsDirectSpaceState3D,
	origin: Vector3,
	desired_dir: Vector3,
	probe_dist: float,
	exclude: Array[RID] = [],
	collision_mask: int = 1
) -> Vector3:
	var flat_goal := Vector3(desired_dir.x, 0.0, desired_dir.z)
	if flat_goal.length_squared() < 0.00001:
		return Vector3.ZERO
	flat_goal = flat_goal.normalized()

	var weighted := Vector3.ZERO
	var total := 0.0
	var eye := origin + Vector3(0.0, 0.6, 0.0)
	for i in range(8):
		var angle: float = float(i) * TAU / 8.0
		var u := Vector3(cos(angle), 0.0, sin(angle))
		var interest: float = maxf(0.05, u.dot(flat_goal))
		var danger := 0.0
		if space != null:
			var q := PhysicsRayQueryParameters3D.create(eye, eye + u * probe_dist, collision_mask, exclude)
			var hit: Dictionary = space.intersect_ray(q)
			if not hit.is_empty():
				var hit_pos: Vector3 = hit["position"]
				danger = clampf(1.0 - eye.distance_to(hit_pos) / maxf(0.05, probe_dist), 0.0, 1.0)
		if danger > 0.7:
			continue
		var score: float = interest * (1.0 - danger)
		weighted += u * score
		total += score
	return weighted.normalized() if total > 0.0001 else flat_goal


static func orbit_direction(self_pos: Vector3, target_pos: Vector3, preferred_radius: float, sign_dir: float = 1.0) -> Vector3:
	var delta := Vector3(target_pos.x - self_pos.x, 0.0, target_pos.z - self_pos.z)
	var dist: float = delta.length()
	if dist < 0.0001:
		return Vector3.FORWARD
	var radial: Vector3 = delta / dist
	var tangent := Vector3(-radial.z * sign_dir, 0.0, radial.x * sign_dir)
	var radial_w: float = clampf((dist - preferred_radius) / maxf(0.5, preferred_radius), -1.0, 1.0)
	return (radial * radial_w + tangent * 0.75).normalized()


class Brain extends RefCounted:
	const PATROL := "patrol"
	const STRAFE := "strafe"
	const TELEGRAPH := "telegraph"
	const STRIKE := "strike"
	const RECOVER := "recover"

	var state: String = PATROL
	var waypoints: Array[Vector3] = []
	var wp_index: int = 0
	var timer: float = 0.0
	var memory_sec: float = 0.0
	var last_seen: Vector3 = Vector3.ZERO

	func step(
		actor_id: int,
		self_pos: Vector3,
		forward: Vector3,
		target_pos: Vector3,
		has_los: bool,
		pool: TokenPool,
		dt: float,
		telegraph_sec: float = 0.45,
		recover_sec: float = 0.65
	) -> Vector3:
		var to_target := Vector3(target_pos.x - self_pos.x, 0.0, target_pos.z - self_pos.z)
		var dist: float = to_target.length()
		var in_cone: bool = dist < 14.0 and (dist < 0.001 or forward.normalized().dot(to_target / maxf(0.001, dist)) >= 0.35)
		var sees: bool = has_los and in_cone
		if sees:
			last_seen = target_pos
			memory_sec = 2.5
		elif memory_sec > 0.0:
			memory_sec = maxf(0.0, memory_sec - dt)

		match state:
			PATROL:
				if sees:
					state = STRAFE
					return Vector3.ZERO
				if waypoints.is_empty():
					return Vector3.ZERO
				var wp: Vector3 = waypoints[wp_index % waypoints.size()]
				var to_wp := Vector3(wp.x - self_pos.x, 0.0, wp.z - self_pos.z)
				if to_wp.length() < 0.65:
					wp_index = (wp_index + 1) % waypoints.size()
				return to_wp.normalized() * 0.65 if to_wp.length() > 0.01 else Vector3.ZERO

			STRAFE:
				if not sees and memory_sec <= 0.0:
					if pool != null:
						pool.release(actor_id)
					state = PATROL
					return Vector3.ZERO
				var goal: Vector3 = target_pos if sees else last_seen
				if sees and dist <= 3.6 and (pool == null or pool.try_acquire(actor_id)):
					state = TELEGRAPH
					timer = telegraph_sec
					return Vector3.ZERO
				return EnemyAI.orbit_direction(self_pos, goal, 4.2, 1.0 if (actor_id % 2) == 0 else -1.0)

			TELEGRAPH:
				timer -= dt
				if timer <= 0.0:
					state = STRIKE
					timer = 0.22
				return Vector3.ZERO

			STRIKE:
				timer -= dt
				if timer <= 0.0:
					if pool != null:
						pool.release(actor_id)
					state = RECOVER
					timer = recover_sec
				return forward.normalized() * 1.65

			RECOVER:
				timer -= dt
				if timer <= 0.0:
					state = STRAFE if sees else PATROL
				return Vector3.ZERO

		return Vector3.ZERO
```

## Performance & Determinism Traps

- **Query `get_world_3d().direct_space_state` inside `_physics_process(dt)`**: Ray queries against `PhysicsDirectSpaceState3D` are locked outside the physics tick.
- **Release tokens when freeing enemies**: Call `pool.release(get_instance_id())` inside `_exit_tree()` so defeated enemies never leak attack tokens.
- **Expose speeds and telegraph windows in `tuning.json`**: Read via `Tuning.value("enemy_telegraph_sec", 0.45)` so balance passes and `audit_game` keep tuning bounds clean.

## Verification Checklist

1. Write unit/play tests in `Assets/Game/Tests/` verifying `Brain` transitions (`patrol -> strafe -> telegraph -> strike -> recover`) and `TokenPool` concurrency caps.
2. Run `compile`, `test_play`, and `audit_game` to confirm zero warnings and valid `level.json` patrol paths.

## Official references

- Andrew Fray (Game AI Pro 2, Ch. 18 — Context Steering)
- Craig Reynolds (GDC 1999 — Steering Behaviors)
- DOOM 2016 Encounter Token Pacing (GDC 2017)
