Skip to content

About

VisionFieldMesh was created as a versatile, editor-friendly tool to help developers prototype and implement enemy vision and detection logic quickly.

Topics

Resources

Stars

45 stars

Watchers

1 watching

Forks

Repository files navigation

🧠 Vision Field System for Unity

VisionFieldMesh is a modular field-of-view (FOV) system for Unity. It combines a procedural vision mesh that is clipped by obstacles with a matching target detector that checks line of sight and raises events when a target enters or leaves the field.

It supports six vision shapes, is configured entirely in the Inspector, and previews in the Scene view outside Play Mode. Use it for enemies, turrets, NPCs, guards, and other AI perception.

Watch the demo

Watch on YouTube

📽️ Demo Preview

Shape Class Preview
Circle / Sector CircleShape
Arrow ArrowShape
Half Ellipse HalfEllipseShape
Offset Triangle OffsetTriangleShape
Square RectangleShape
Rhombus RhombusShape

📽️ Demo Videos

1.3.mp4
1.2.mp4
1.1.mp4

⚙️ Features

  • One shape, drawn and detected the same way: six shapes, each described once and shared by the mesh and the detector.
  • Cheap detection: shape formula plus a few line-of-sight rays, 10 times a second.
  • GPU occlusion: the field is hidden behind walls per pixel by a shader; the mesh never changes, and 50 cones cost about 0.9 ms CPU and 0.16 ms GPU per frame in the Editor.
  • Shader effects: soft edges at walls, an outline glow and waves travelling outwards from the observer.
  • RaycastOffset keeps the field's edge slightly in front of walls.
  • Target detection with shape tests, height limits, and line-of-sight raycasts.
  • Events: OnTargetDetected and OnTargetLost fire only when the visible target changes.
  • Debug gizmos: the shape outline in yellow, free rays in green, clipped rays in red, and the current target in cyan.
  • Editor-time preview: the [ExecuteAlways] mesh updates as you edit the shape; a Rebuild button forces it.
  • Extensible: a new shape is one VisionShape class and a prefab.

🔄 What's New

Compared with the first version of the project:

Area Before Now
Engine Unity 2022.3 Unity 6000.5.3f1, URP 17.5
Shapes A mesh class and a detector class per shape, each with its own math One VisionShape per prefab, shared by the mesh, the detector and the GPU pass
Walls Mesh vertices clipped by raycasts every frame Static mesh; walls hidden per pixel on the GPU (raycast clipping kept as a fallback)
Detection Separate per-shape checks Shape formula + up to 3 line-of-sight rays, 10 times a second, nearest target wins
Look Toony Colors material VisionField/Cone shader: soft wall edges, outline glow, waves
Tests None 225 EditMode and PlayMode tests, including GPU-vs-physics and rendered-pixel checks
Tooling — AI Unity Pipeline rules and skills, Unity CLI and MCP

Bugs fixed along the way: level restart and path handling, HUD speed parsing (1.5 and 1,5), weapon states that kept running after the target was lost or the object was destroyed, shapes cut short at their corners and arc tops, and Unity 6.5 console errors in third-party plugins.

🔍 How It Works

Each vision prefab carries one shape and two components that read it:

flowchart LR
    subgraph Prefab["Vision prefab (Resources/VisionCone)"]
        Field["VisionField<br/>the shape"]
        Mesh["VisionFieldMesh<br/>draws the field"]
        Detector["VisionFieldDetector<br/>finds targets"]
        Field --> Mesh
        Field --> Detector
    end
    Obstacles[("Obstacle layer")]
    Targets[("Target layer")]
    Occlusion["VisionOcclusion<br/>(GPU, all cones)"]
    Occlusion -- "wall cross-section at eye height" --> Obstacles
    Occlusion -- "polar distance atlas" --> Mesh
    Detector -- "OverlapSphere + shape formula" --> Targets
    Detector -- "line-of-sight raycast" --> Obstacles
    Detector -- "OnTargetDetected / OnTargetLost" --> VisionAI
    VisionAI --> WeaponAI["WeaponAI<br/>aim → shoot → idle"]
Loading
  • VisionField holds the shape (VisionShape: circle/sector, rectangle, rhombus, arrow, offset triangle, half ellipse). The shape knows its outline, its reach and a Contains(point) formula, and tests check that the formula and the drawn outline agree.
  • VisionFieldMesh draws a static triangle fan from the shape's centre to its outline with the VisionField/Cone shader. In Gpu mode (default) walls are handled per pixel; CpuRaycasts is a fallback that clips the vertices with raycasts.
  • VisionOcclusion does the GPU work once per frame for up to 64 cones: it draws where obstacle colliders cross the plane at eye height into a top-down mask, then measures, for every cone and 512 directions, the distance to the first wall. The cone shader reads that distance and fades out everything behind it. Low boxes below eye height and roofs above it don't block, exactly like a horizontal raycast.
flowchart LR
    Colliders[("Obstacle colliders<br/>around the cones")]
    Slice["1. Slice pass<br/>wall cross-section at eye height<br/>→ 1024² top-down mask"]
    Polar["2. Polar pass<br/>distance to the first wall<br/>→ 512 angles × 64 cones atlas"]
    Cone["3. Cone shader<br/>hides pixels behind walls,<br/>edge glow and waves"]
    Colliders --> Slice --> Polar --> Cone
Loading
  • VisionFieldDetector detects analytically, 10 times a second by default: one overlap query finds candidates, the shape's formula checks whether each is inside, and only those get up to three line-of-sight rays. It returns the nearest visible enemy. 50 observers watching 50 enemies cost about 0.3 ms per detection pass in the Editor.

🚀 Quick Start (demo)

  1. Open the project in Unity 6000.5.3f1.
  2. Open Assets/Scenes/Boot.unity and enter Play Mode. The boot scene loads Game.unity automatically.
  3. In the HUD, choose a vision shape from the dropdown, enter a movement speed, and press Start.
  4. The player follows the level path. When an enemy enters the field, the turret aims and fires, and the enemy disappears with a VFX.

🧰 Using the System in Your Scene

  1. Create a GameObject (it looks along its forward axis) and add VisionFieldMesh — it adds VisionField, MeshFilter and MeshRenderer. Pick the shape in VisionField and assign the VisionCone_mat material (Assets/Resources/VisionCone/VisionCone_mat.mat, shader VisionField/Cone).
  2. Add VisionFieldDetector and set Target Mask and Obstacle Mask; set the same Obstacle Mask on the mesh.
  3. The field updates in the Scene view as you edit the shape; Rebuild forces it.
  4. Enable Is Show Debug to see the outline, clip rays and current target as gizmos when the object is selected.
  5. Subscribe to the detector events:
_detector.OnTargetDetected += enemy => Debug.Log($"Seen: {enemy.name}");
_detector.OnTargetLost += enemy => Debug.Log($"Lost: {enemy.name}");

Targets are found by component: a collider on the target layer must have an Enemy component (Code.Enemy). Keep the owner's own colliders off the obstacle layers — the demo player uses a separate Player layer so its field never clips against itself.

Ready-made prefabs for all six shapes are in Assets/Resources/VisionCone/.

📐 Shape Parameters

Mesh settings (VisionFieldMesh): Cone Material, Sort Order, Occlusion Mode (Gpu, CpuRaycasts, None), Obstacle Mask, Raycast Offset. Material settings (VisionField/Cone): base, edge and wave colours, edge width, occlusion softness, centre fade, wave spacing, speed and width. Detector settings (VisionFieldDetector): Target Mask, Obstacle Mask, Detection Interval (seconds between checks, default 0.1), optional height window (Height Below / Height Above). Every shape also has Segments (outline resolution).

Shape Parameters
Circle / Sector (CircleShape) Range, Angle (up to 360°)
Arrow (ArrowShape) Width, Height, Tilt Angle (−45…45°)
Half Ellipse (HalfEllipseShape) Width, Height, Pre Length, Length, Center Offset
Offset Triangle (OffsetTriangleShape) Width, Height, Center Offset
Square (RectangleShape) Width, Height
Rhombus (RhombusShape) Side Length, Angle Degrees (10…170°)

🏗️ Project Architecture

Tech stack

Area Choice
Engine Unity 6000.5.3f1, URP 17.5.0 (Forward; depth/opaque textures and HDR off)
Dependency injection Zenject / Extenject (ProjectContext + SceneContext)
Async UniTask
Tweens DOTween
Inspector & editor tools Odin Inspector (attributes, OdinEditorWindow, serialization)
UI uGUI 2.5 + TextMesh Pro, View / Presenter split
Tests Unity Test Framework 1.7 (EditMode + PlayMode)
Asset loading Resources through IInstantiator.InstantiatePrefabResource
Saves PlayerPrefs + Odin JSON serialization

Boot and game flow

sequenceDiagram
    participant Boot as Boot.unity
    participant PC as ProjectContext<br/>(BootstrapInstaller)
    participant Game as Game.unity<br/>(GameInstaller)
    participant GS as GameStarter
    participant HUD as LevelView / LevelPresenter
    participant LC as LevelController

    Boot->>PC: Zenject creates ProjectContext
    PC->>PC: bind factories, providers, services
    PC->>PC: StaticDataService.LoadData()
    PC->>Game: SceneManager.LoadScene("Game")
    Game->>GS: Initialize()
    GS->>GS: load or create PlayerData
    GS->>GS: UI root, camera, player, enemies
    GS->>HUD: create GameHud + LevelPresenter
    HUD->>LC: PlayLevel(visionType, moveSpeed)
    LC->>LC: VisionConeFactory creates the prefab under the player
    LC->>LC: Player.SetTargetDetector → VisionAI
    LC->>LC: PlayerMover.MoveAlongPath(path)
Loading
  • BootstrapInstaller (on Assets/Resources/ProjectContext.prefab) is the app-wide composition root. It binds PlayerFactory, EnemyFactory, VisionConeFactory, UIFactory, the camera, player and enemy providers, PrefsSaveLoadService, PersistenceProgressService, LevelController and StaticDataService.
  • GameInstaller (on SceneContext_Game in Game.unity) holds the scene references (player spawn point, enemy spawn points, LevelPathMover), binds GameStarter and GameUpdater, and forwards Update() to GameUpdater, which drives CameraFollowing.
  • VisionConeFactory loads Resources/VisionCone/<VisionType>. The VisionType enum names must match the prefab names, and the enum order is the HUD dropdown order.
  • VisionAI listens to the detector and drives WeaponAI, a small UniTask state sequence: idle (bobbing via DOTween) → aim and follow the target → shoot (VFX, Enemy.SetDead()) → idle. Each transition cancels the previous one, and everything stops when the weapon is destroyed.

Folder structure

Assets/
├── Code/                         # Game.asmdef (runtime), root namespace "Code"
│   ├── Cameras/                  # CameraFollowing, ICameraProvider
│   ├── Editors/                  # GameEditor.asmdef: path editor, hotkeys, prefab batch tool
│   ├── Enemies/                  # Enemy, EnemyFactory, EnemyProvider
│   ├── Infrastructure/
│   │   ├── BootstrapInstaller.cs # app-wide Zenject installer
│   │   ├── GameInstaller.cs      # Game scene installer
│   │   ├── Factory/              # base Factory, UIFactory
│   │   ├── Services/             # GameStarter, GameUpdater, SaveLoad, PersistenceProgress, StaticData
│   │   └── StaticData/           # ScriptableObject data types
│   ├── Levels/                   # LevelController, LevelPathMover
│   ├── Players/                  # Player, PlayerMover, PlayerFactory, PlayerProvider
│   ├── UI/                       # GameHud, LevelView, LevelPresenter
│   ├── Utilities/Extensions/     # extension methods
│   ├── VisionCone/               # the vision system
│   │   ├── VisionField.cs        # holds the shape
│   │   ├── VisionFieldMesh.cs    # draws it
│   │   ├── VisionFieldDetector.cs # detects inside it
│   │   ├── Shapes/               # VisionShape + 6 shapes, VisionShapeMath
│   │   ├── Occlusion/            # VisionOcclusion: GPU slice mask + polar atlas
│   │   ├── Factory/              # VisionConeFactory, VisionType
│   │   ├── Provider/             # placeholder
│   │   └── VisionAI.cs           # detector → weapon bridge
│   └── Weapon/                   # Weapon (DOTween), WeaponAI (UniTask states)
├── Plugins/                      # Zenject, UniTask, DOTween, Odin Inspector, TextMesh Pro
├── Resources/                    # runtime-loaded prefabs and configs
│   ├── ProjectContext.prefab, SceneContext_*.prefab
│   ├── VisionCone/               # 6 vision prefabs, VisionCone_mat, Shaders/
│   ├── Player/, Enemies/, UI/    # spawned prefabs
│   ├── StaticData/               # ScriptableObject assets
│   └── URP/                      # URP asset and renderer
├── ResourcesStatic/              # art & VFX: Stickman, Hypercasual Action Props, Cartoon FX, Toony Colors Pro
├── Scenes/                       # Boot.unity, Game.unity
└── Tests/                        # EditMode + PlayMode test assemblies

Adding a new vision shape

  1. Create MyShape : VisionShape ([Serializable]) with its parameters, ReachRadius, Contains(point), GetOutlinePoint(t) and GetParameterHash(); the formula and the outline must describe the same area.
  2. In the Editor, create a prefab with VisionField (pick your shape), VisionFieldMesh and VisionFieldDetector in Assets/Resources/VisionCone/.
  3. Add the shape to VisionShapeTests, which checks the formula against the outline.
  4. Add a value to the end of VisionType whose name equals the prefab name. It appears in the HUD dropdown automatically.
  5. Register the shape in VisionPrefabTests and VisionMeshGeometryTests, then run the tests.

🧑‍💻 Editor Tools

Tool Where What it does
Level path editor LevelPathMover inspector Position handles for every path point; add or delete points with hotkeys
Level Path Hotkeys Settings Tools → Level Path Hotkeys Settings Configure the add/delete point keys (default Q / E)
Prefab Batch Editor Window Tools → Prefab Batch Editor Window Apply a material and renderer settings to a whole prefab hierarchy
Rebuild VisionFieldMesh inspector (Odin button) Rebuild the vision mesh in Edit Mode

🧪 Tests

225 automated tests live in Assets/Tests:

Suite Count What it checks
EditMode (Tests.EditMode) 204 Prefab wiring, shape types and layer masks, shape formula vs. outline agreement, GPU occlusion vs. physics (sandbox and the real level), final cone pixels rendered from above, mesh geometry (valid upward triangles, full shape, wall clipping, sector area), detector vs. drawn field (inside seen, outside ignored, walls block, nearest wins, events), shape math, a 50-observer load test, Resources and scene integrity, Zenject bindings, HUD input parsing, save/load
PlayMode (Tests.PlayMode) 21 Boot → Game, PlayLevel for every shape, level restart, the full demo path for every shape, PlayerMover, reloading Game while the weapon aims, 50-cone GPU occlusion cost

Run them from Window → General → Test Runner, or from a terminal while the Editor is open:

unity command test run --mode editor --filter Tests.EditMode --filter-type Assembly
unity command test run --mode playmode --filter Tests.PlayMode --filter-type Assembly --async-tests true
unity command test status --detail failures

🤖 AI-Assisted Development

The project includes the AI Unity Pipeline setup for coding agents:

Part Purpose
CLAUDE.md Project rules for Claude Code: architecture, conventions, Git style, CLI commands, tests
AGENTS.md The same rules for OpenAI Codex
.claude/skills/feature-cycle Implement a feature in a feature/<name> branch, verify it in Unity, and leave Docs/Features/<name>/Status.md
.claude/skills/chat-notes Save a dated summary of a chat to Docs/
com.unity.pipeline Unity Pipeline package: lets the Unity CLI and MCP drive the open Editor
Unity MCP unity mcp --project-path <project> registered as an MCP server for the agent
Unity agent plugin Official unity@unity-agent-plugin skills for Claude Code

To connect your own agent, install the Unity CLI, open the project, then run unity mcp configure <client> --project-path <path-to-project> (see unity mcp configure --list).

⚠️ GPU Occlusion Limits

  • One cross-section for all cones, at their average eye height: cones on very different floors share it.
  • Walls block from both sides; trigger colliders are ignored; box, sphere, capsule and mesh colliders are supported.
  • The mask covers all cones (up to 256 m across, 1024 texels), so very spread-out cones get a coarser mask.
  • Up to 64 GPU-occluded cones; more are drawn without occlusion (a warning is logged).
  • The slice and polar passes need shader model 4.5 (raw buffers): DX11/12, Vulkan, Metal, GLES 3.1+.

🔁 Level Behaviour

  • Pressing Start again restarts the level: the previous vision field is removed, enemies are revived, and the player starts the path from the beginning with the newly selected shape.
  • The HUD number is the movement speed (units per second, minimum 0.1). Both 1.5 and 1,5 are accepted.
  • Every detector reports the nearest visible target.

✅ Requirements

  • Unity 6000.5.3f1 (the pinned version) with URP 17.5
  • Odin Inspector (vision components use its attributes and buttons). The bundled version predates Unity 6.5 and logs editor exceptions on load; update it from the Asset Store.
  • Zenject/Extenject, UniTask and DOTween for the demo game (included in Assets/Plugins)

📄 License

MIT © 2025 SinlessDevil

About

VisionFieldMesh was created as a versatile, editor-friendly tool to help developers prototype and implement enemy vision and detection logic quickly.

Topics

Resources

Stars

45 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages