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.
- ai
- enemy
- npc
- steering
- patrol
- telegraph
- combat
- attack-tokens
- perception
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 → active → recovery combat phases, and an attack-token coordinator so crowds flank readably instead of stacking into a single capsule:
- 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. - Patrol Routes in
level.json: Read waypoints fromLevelData.load_default().path("guard_loop")rather than hardcoding magic coordinates in scripts. - Telegraph Silhouettes & Recovery Windows: Give every lunge or projectile a clear
0.4–0.65 swindup before activating hitboxes, plus a0.6 spost-strike recovery window.
Mathematical & Algorithmic Core
- 8-Slot Context Steering: For unit directions
u_i = (cos (τ i)/(8), 0, sin (τ i)/(8)), compute interestI_i = max(0.05, u_i · g)and obstacle dangerD_i ∈ [0, 1]from short horizontal ray probes; sumΣ u_i I_i (1 - D_i)across unblocked slots (D_i ≤ 0.7). - Orbit Flank Vector: Combine radial spacing error
clamp((d - r_pref) / r_pref, -1, 1)with tangent(-r_z, 0, r_x)so enemies waiting for an attack token circle atpreferred_radius.
Engine Implementation
Typed Context Steering, Token Pool & Enemy Brain (Assets/Game/Scripts/gameplay/enemy_ai.gd)
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_stateinside_physics_process(dt): Ray queries againstPhysicsDirectSpaceState3Dare 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 viaTuning.value("enemy_telegraph_sec", 0.45)so balance passes andaudit_gamekeep tuning bounds clean.
Verification Checklist
- Write unit/play tests in
Assets/Game/Tests/verifyingBraintransitions (patrol -> strafe -> telegraph -> strike -> recover) andTokenPoolconcurrency caps. - Run
compile,test_play, andaudit_gameto confirm zero warnings and validlevel.jsonpatrol 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)
Playable Godot 4 games made with GameCrew
Launch a real browser build using this engine and inspect its controls or fork its project tree.

Fernlight
Raise a carved whistle to your lips in a fog-drowned forest, coax a glowing bird onto your open hand, and point to send it off to light the dark.
More Godot 4 techniques
CharacterBody3D Slopes, Snap & Coyote Jump in Godot 4 →
Crisp Godot 4 CharacterBody3D locomotion combining floor_snap_length, apex hang gravity, jump-cut, coyote time, and zero-arg move_and_slide.
Frame-Rate-Independent Springs, Squash-Stretch & Ribbon Trails in Godot 4 →
Typed GDScript 4 second-order damped springs, volume-preserving visual squash-stretch, Eiserloh T^2 FastNoiseLite camera trauma, and ImmediateMesh sword/dash ribbon trails.
Stylized Water, Gerstner Waves & Depth Shoreline Foam in Godot 4 Compatibility →
Godot 4.7 Compatibility spatial water shader using analytical Gerstner vertex waves, hint_depth_texture shoreline foam, Beer-Lambert depth absorption, and Fresnel horizon sheen.
Raymarched Volumetric Cloud Sky in Godot 4 Compatibility (WebGL 2) →
Compatibility-safe sky shader in Godot 4.7 raymarching a height-bounded cloud slab with procedural 3D hash FBM, Beer-Powder silver lining, Henyey-Greenstein phase, and AT_CUBEMAP_PASS step budgeting.
Use verified techniques inside a real game
Describe your game idea for free or connect an MCP assistant to search and contribute techniques.