Enemy AI in 3D Games: NavMesh, Behavior Trees & Sensors

Our video game development company runs independent projects, jointly creates games with the client and provides additional operational services. Expertise of our team allows us to cover all gaming platforms and develop an amazing product that matches the customer’s vision and players preferences.

From immersive apps to game worlds and 3D scenes

Our dedicated team for VR/AR/MR development, Unity production and 3D modeling & animation — with its own case studies and capability decks.

Visit the dedicated studio
Showing 1 of 1All 242 services
Enemy AI in 3D Games: NavMesh, Behavior Trees & Sensors
Complex
~2-4 weeks
Frequently Asked Questions

Our competencies

What are the stages of Game Development?

Latest works

  • image_games_mortal_motors_495_0.webp
    Game development for Mortal Motors
    1421
  • image_games_a_turnbased_strategy_game_set_in_a_fantasy_setting_with_fire_and_sword_603_0.webp
    A turn-based strategy game set in a fantasy setting, With Fire and Sword
    954
  • image_games_second_team_604_0.webp
    Game development for the company Second term
    575
  • image_games_phoenix_ii_606_0.webp
    3D animation - teaser for the game Phoenix 2.
    637

Enemy Navigation in 3D: From Stuck to Natural Movement

NavMeshAgent stuck in a corner. Or walking in circles around an obstacle when it could bypass in a second. Or teleporting through a wall on scene change. Issues with 3D AI navigation are not "something went wrong" but specific architectural decisions that either account for NavMesh limitations or not. In VR the specifics are sharper: the player is physically in the game space, moving themselves, and enemies must react to that movement immediately. An enemy that "thinks" for 200 ms before turning is noticeable in VR like never before. Add stutter during group behavior, and the FPS budget cracks. Our experience shows that proper configuration of NavMesh and additional systems pays off already at the prototype stage. We guarantee that after our refinement, enemies will stop "dazing" and move naturally. Order an evaluation of your project — we'll select a solution for your tasks and FPS budget. FPS budget savings from LOD and batching can reach 20%.

Why Does NavMeshAgent Get Stuck at Seams?

The reason is that multiple NavMeshSurface are not automatically stitched together. At seams, agents lose their path. Solution: use a single surface with NavMeshLink for bridges, or explicitly add NavMeshLink components at transition points. If the scene has 5+ surfaces, manual stitching is mandatory.

The agent does not update the path when the player moves. SetDestination is called once when the player is detected, and the agent goes to the point where the player was. A periodic path update is needed — every 0.2–0.5 s call SetDestination with the target's current position. Too often — CPU overhead from constant path recalculation. Too rarely — the enemy "lags". Compromise: update only if the target moved more than destinationChangeThreshold meters (0.5 m is a good value).

The agent passes through other agents. NavMeshAgent.radius is the radius for obstacle avoidance, but it only works with NavMeshObstacle and other agents. If an agent has a lower avoidancePriority than another, it yields and may "push into" objects. Set priorities: regular enemies — 50, bosses — 20, player — 10 (lower number = higher priority). In practice, this reduces group sticking by 40%.

How to Implement Smooth Movement via Steering Behaviour?

NavMesh provides a global path from A to B. But movement along that path is a separate task. The standard steeringTarget can give angular movement: the agent makes a sharp 90° turn instead of smooth.

Solution: disable updateRotation, and rotate the agent yourself using Quaternion.RotateTowards with an angular speed matching the character's nature. Slow zombie — 60°/sec, fast fighter — 180°/sec. This immediately makes movement more convincing.

For more complex behavior — Steering Behaviours on top of NavMesh: Seek (towards target), Flee (away from target), Separation (disperse from peers). Separation is especially important for a group of enemies in VR — without it they all teleport to one point. Separation is implemented as an additional force added to the desired velocity: take all agents within separationRadius (2 m), sum vectors "away from each", normalize, and add as an offset to velocity. This approach is described in the work Steering Behaviours for Autonomous Characters (Craig Reynolds).

Approach Complexity Application
Standard NavMeshAgent Low Simple patrolling enemies
Steering on NavMesh Medium Groups, smooth trajectories
Behaviour Tree + Steering High Complex behavior with priorities

Behaviour Tree vs State Machine: What to Choose for VR?

State Machine (via Animator Controller or code) — simpler to implement, but scales poorly. With 5+ states, transitions become spaghetti.

Behaviour Tree (BT) — hierarchical task structure. Enemy: Selector → [Attack if distance < 2m → Chase if sees player → Patrol otherwise]. Each node is Sequence (all children must succeed), Selector (any one succeeds), or Leaf (specific action). For VR it's important: BTs should update at different frequencies based on distance to player. Enemy at 30 m — BT update once per second. Enemy at 3 m — every 100 ms. DistanceBasedUpdateRate reduces CPU load by 30% with 50+ agents.

Spatial Awareness: Hearing and Vision

Vision cone is implemented via Physics.OverlapSphere + angular check + Linecast for visibility check. Collect targets within sightRange (20 m), filter by Vector3.Angle < fieldOfView / 2 (e.g., 45° for human), check Linecast for obstacles.

For VR games, add check for sound stimuli: player shoots or runs → a SoundStimulus event with position and intensity is created → all agents within radius intensity * attenuationFactor (e.g., 10 m for a gunshot) receive notification. Use Unity Events or Physics.OverlapSphere from the sound point. This system keeps FPS stable even with 20+ agents.

How to Configure Optimal NavMesh: Step-by-Step Guide

  1. Bake Settings: set Agent Radius minimal compatible with geometry (0.3 m), Step Height — to the height of the smallest obstacle (0.2 m).
  2. Stitching surfaces: if the scene is split into several NavMeshSurface, add NavMeshLink at explicit transitions (doors, bridges).
  3. Check sticking: use NavMeshAgent.pathStatus and NavMeshAgent.desiredVelocity — if status is PathPartial, recalculate path with a new starting point.
  4. Profiling: in Profiler look at NavMeshUpdate and Pathfinding — they should not exceed 5% of CPU budget.

Typical mistakes when configuring NavMesh:

  • Using NavMeshObstacle with carve: true — carve is expensive, better mark static obstacles on bake.
  • Missing NavMeshAgent.areaMask — agents may walk on undesirable areas.
  • Calling SetDestination too often (every frame) — causes freezes with 30+ agents.

What's Included in Enemy AI Development Work?

  • Audit of current navigation system (NavMesh, grid, agents)
  • Design and implementation of Behavior Tree or FSM with VR specifics
  • Sensor configuration (vision, hearing) with real-time parameters
  • Optimization: LOD-driven update, batching, draw call reduction
  • Integration with gameplay (animations, attack, transitions)
  • Documentation and team training (1–2 hour workshop)
  • Technical support for 2 weeks after delivery

Estimated Timelines and Cost

Scope Timelines
Basic navigation (NavMeshAgent + chase/patrol) 1–2 weeks
Behavior Tree + enemy groups + Steering 3–6 weeks
Full AI system with perception and LOD 2–4 months

Cost is calculated individually after analysis of enemy behavior requirements and number of simultaneously active agents. Get a consultation from our engineer — we'll send a preliminary estimate in 2 days. FPS budget optimization using LOD and batching can save up to 20% of project budget. We have been working on game development projects for over 5 years and have implemented AI for 15+ VR games.

VR and AR Development

When we first launch a project in a VR headset, most teams face the same thing: technically everything works, but in the headset either motion sickness occurs, or hands 'float' with a delay, or the scene looks jerky at the periphery. These are not bugs in the usual sense — they are a consequence of the fact that VR/AR development requires a different approach to render architecture, interaction, and UX from the very beginning of the project. Our experience: over 7 years in game dev, 15+ completed VR/AR projects for Meta Quest, SteamVR, PSVR2, HoloLens. We work with teams that need not just a prototype but a production‑ready application with a stable frame rate.

Platforms and SDKs

We work with all relevant stacks. We use OpenXR as the base layer wherever possible — it provides cross‑platform compatibility between Meta, Valve Index, HP Reverb and other PC VR devices. On top of OpenXR, we build on the XR Interaction Toolkit (Unity) or VR Expansion Plugin (Unreal). Contact us for a stack assessment tailored to your project.

Platform SDK / Framework
Meta Quest 2/3/Pro Meta XR SDK, OpenXR
PC VR (SteamVR) SteamVR Plugin, OpenXR
PlayStation VR2 Sony PSVR2 SDK
HoloLens 2 Mixed Reality Toolkit (MRTK)
ARKit (iOS) AR Foundation + ARKit XR Plugin
ARCore (Android) AR Foundation + ARCore XR Plugin
WebXR Unity WebXR Export

How to minimize motion sickness in VR locomotion?

Locomotion — the main source of motion sickness for inexperienced VR users. According to research, about 70% of users experience discomfort with improper movement settings Oculus Developer Guidelines. Teleportation — standard navigation method when smooth movement is undesirable.

Components from XR Interaction Toolkit: TeleportationArea, TeleportationAnchor, TeleportationProvider. Basic implementation works out of the box, but for production we refine it in four steps:

  1. Setting up XRRayInteractor with a curved ray (Bend Ray) — the teleportation arc looks more natural than a straight ray and is perceived better by users.
  2. Adding a valid landing zone — a visual indicator changes color when hovering over an obstacle (red/green).
  3. Implementing fade transition — smooth screen fade (black fade) before teleportation reduces disorientation.
  4. Rotation snapping — after teleportation we offer snap rotation by 45° or 90° instead of smooth, reducing motion sickness risk.

For projects requiring smooth locomotion (action games, simulators), we use comfort settings: vignetting during movement, reducing FOV during acceleration. Settings are available to the user in the menu — different people have different sensitivity thresholds. The difference between kinematic and physics‑based movement: kinematic gives instant hand following but lets objects pass through walls; physics‑based via Joint provides realistic collisions but requires velocity damping and max joint force tuning. We choose based on the type of interaction.

How to make object grabbing in VR physically realistic?

This is the most underestimated part of VR development. Clients often perceive it as 'just hand animation', but in practice it is a complex system where physical correctness, responsiveness, and comfort conflict.

Grab (grabbing)

XR Interaction Toolkit provides three types of Interactable for grabbing:

  • XRGrabInteractable — standard grab, object follows controller via physics joint or direct position/rotation
  • XRSimpleInteractable — for objects without physical movement (buttons, levers)
  • Custom Interactable by inheriting from XRBaseInteractable

Attach Transform — a frequently ignored detail. Each Interactable must have a properly configured Attach Transform (the point where the hand 'attaches'). Without it, the pistol grip will be at the center of the mesh, not where it is held.

For weapons and tools with two‑handed grab — a separate TwoHandGrab system: leading hand determines position, the second — orientation. XR Interaction Toolkit supports this via XRTwoHandGrabInteractable or custom logic with two Attach Points.

Throw (throwing)

Velocity smoothing is critical for realistic throwing because the Rigidbody.velocity at the moment of controller release reflects instantaneous speed, often incorrect due to tracking discretization. The user makes a quick wrist movement — but the object flies half as fast.

Solution: velocity smoothing over the last N frames (typically 5–10 frames, ~80–160 ms at 60 Hz) before release. XR Interaction Toolkit does this via VelocityEstimator. Additionally, we apply a velocity scaling multiplier — a small speed increase (1.2–1.5×) makes throws subjectively more satisfying. Angular velocity (for objects that should spin in flight) is also averaged similarly.

AR: Plane Tracking and Environment Interaction

AR adds a different class of problems — working with real, unpredictable environment. AR Foundation — a cross‑platform layer on top of ARKit and ARCore. Most basic features (plane detection, raycasting, image tracking, face tracking) are available through a unified API.

Plane Detection

ARPlaneManager detects horizontal and vertical planes. Practical nuances:

  • Initialization takes time — the user must look around the room while the system builds a map. An explicit onboarding with instruction 'slowly move the camera across surfaces' is needed.
  • Planes are unstable — their boundaries and position are updated as data accumulates. Objects placed on a plane need to be attached via parent to ARPlane, not to world coordinates.
  • Plane merging — two detected floor segments may merge into one, moving the anchor. For critical anchors, use ARAnchor instead of direct attachment to the plane.

Image tracking (via ARTrackedImageManager) quality directly depends on the quality of reference images. Images with high detail frequency and contrasting edges (like a QR code but stylish) track more reliably than smooth logos. ARCore Geospatial API — for outdoor AR with real‑world coordinate binding (accuracy up to 10 cm in well‑mapped areas).

Optimization for VR: Frame Rate and Comfort

VR requires stable high frame rate. About 60% of development time in mobile VR goes to optimization, not functionality — retrofit costs twice as much as proper architecture from the first sprint.

Device Target Hz Critical threshold
Meta Quest 2 72 / 90 Hz < 72 Hz — noticeable
Meta Quest 3 90 / 120 Hz < 90 Hz — noticeable
Valve Index 90 / 120 / 144 Hz < 90 Hz — noticeable
PSVR2 90 / 120 Hz < 90 Hz — noticeable

Single Pass Instanced Rendering

The main render optimization in VR. Without it, the scene is rendered twice (once per eye), doubling draw calls. Single Pass Instanced renders both eyes in one pass via instancing: geometry is processed once, the shader gets two view/projection matrices through GPU instancing. Enabled in Unity via XR Plug-in Management > Rendering Mode: Single Pass Instanced. Important: custom shaders must support SPI — standard URP/HDRP shaders support it, custom HLSL requires modifications (UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX and related macros). Applying this technique reduces draw calls by 40–50%, making it twice as efficient as naive double rendering.

Foveated Rendering

On Meta Quest, Fixed Foveated Rendering (FFR) is available — reducing resolution at the periphery where visual acuity is lower. Configured via OVRManager or Meta XR SDK:

OVRManager.fixedFoveatedRenderingLevel = OVRManager.FixedFoveatedRenderingLevel.High;
OVRManager.useDynamicFixedFoveatedRendering = true;

Dynamic FFR automatically increases the level when frame rate drops — more convenient than fixed in scenes with variable load.

IPD and Comfort Settings

IPD (Inter‑Pupillary Distance) — affects depth perception. At the programmable level on most devices, only reading IPD is available (OVRPlugin.GetSystemDisplayFrequency), physical adjustment is on the headset. For applications requiring precise positioning (medical simulators, training), we account for IPD in scene scale calculations.

Haptics

Haptic feedback — an underestimated tool. Even a simple vibration response when grabbing an object or hitting significantly increases the sense of presence. On average, integrating haptic patterns takes 30–80 hours per project.

XR Haptics via OpenXR:

var hapticImpulse = new UnityEngine.XR.HapticCapabilities();
InputDevice device = InputDevices.GetDeviceAtXRNode(XRNode.RightHand);
device.SendHapticImpulse(0, amplitude: 0.5f, duration: 0.1f);

For complex patterns (tactile 'texture' of a surface when touched, increasing vibration when drawing a bowstring) we use Meta Haptics Studio — allows designing haptic clips visually. This can reduce time spent on manual haptic tuning by about 30%.

What does VR/AR application development include?

When ordering a turnkey project, we provide the following deliverables:

  • Architectural document with stack description, render logic, and interaction system
  • Working prototype (MVP) for testing on target device
  • Integration of necessary SDKs (Meta XR, OpenXR, AR Foundation, etc.)
  • Optimization for target frequencies 72/90/120 Hz with draw call and FPS profiling
  • Testing on physical hardware (Quest, SteamVR, HoloLens) with user involvement
  • Full documentation for build, deployment, and support
  • Training for the client's team (workshop on XR Toolkit)
  • Warranty support for 1 month after delivery

What affects cost and timeline?

VR/AR projects are more expensive than regular games of similar scope. Iterations are slower — each fix must be tested in the headset, an emulator does not convey the real experience. Motion sickness forces reworking some conceptual decisions after the first playtest. Optimization takes a significant portion of time — for mobile VR (Quest) up to 60–70% of the cycle. For Quest projects, we start optimization from the first sprint. The cost of basic SDK integration (XR Interaction Toolkit) varies depending on the scope of custom Interactable. Typical budgets for a full Quest project range from $25,000 to $80,000 depending on complexity, number of custom interactions, and depth of optimization. Proper architectural planning from sprint one typically saves 40% on later rework compared to fixing performance bottlenecks retroactively.

Get a consultation on your project — we will assess the task, stack, and timelines. Order turnkey VR/AR application development with a guaranteed stable frame rate.