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

Latest commit

Β 

History

111 Commits

Folders and files

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 Mesh + Detector pair Preview
Circle / Sector VisionCircleMesh + TargetCircleDetector
Arrow VisionArrowMesh + TargetArrowDetector
Half Ellipse VisionHalfEllipseMesh + TargetHalfEllipseDetector
Offset Triangle VisionOffsetTriangleMesh + TargetOffsetTriangleDetector
Square VisionSquareMesh + TargetSquareDetector
Rhombus VisionRhombusMesh + TargetRhombusDetector

πŸ“½οΈ Demo Videos

1.3.mp4
1.2.mp4
1.1.mp4

βš™οΈ Features

  • 🧩 Procedural vision mesh for six shapes, rebuilt only when its parameters or transform change.
  • 🧱 Obstacle clipping: every edge ray is raycast against an obstacle mask, so the field stops at walls.
  • πŸŒ— RaycastOffset pulls the clipped edge back from surfaces to avoid z-fighting and clipping.
  • 🎯 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: free rays in green, blocked rays in red, rays that hit targets in yellow, and detected targets in cyan.
  • πŸ› οΈ Editor-time preview: [ExecuteAlways] meshes with Create Mesh / Delete Mesh buttons.
  • ♻️ Extensible: a new shape is one mesh class, one detector class, and a prefab.

πŸ” How It Works

Each vision prefab carries two components that work independently:

flowchart LR
    subgraph Prefab["Vision prefab (Resources/VisionCone)"]
        Mesh["BaseVisionMesh subclass<br/>draws the field"]
        Detector["BaseTargetDetector subclass<br/>finds targets"]
    end
    Obstacles[("Obstacle layer")]
    Targets[("Target layer")]
    Mesh -- "edge raycasts" --> Obstacles
    Detector -- "OverlapSphere / shape test" --> Targets
    Detector -- "line-of-sight raycast" --> Obstacles
    Detector -- "OnTargetDetected / OnTargetLost" --> VisionAI
    VisionAI --> WeaponAI["WeaponAI<br/>aim β†’ shoot β†’ idle"]
Loading
  • BaseVisionMesh owns the MeshFilter and MeshRenderer. Each subclass builds its outline from _precision / _segments directions, raycasts each one against _obstacleMask, and writes the vertices, triangles, normals and UVs into a dynamic mesh. Shadows, light probes and occlusion are turned off on the renderer.
  • BaseTargetDetector calls FindVisibleTarget() in every Update(), compares the result with the previous frame and raises OnTargetLost and OnTargetDetected.
  • RaycastTargetDetector (Arrow, Half Ellipse, Offset Triangle, Square, Rhombus) casts a ray from the shape centre to every outline point β€” the same fan the mesh is built from β€” and returns the nearest enemy that no obstacle hides. TargetCircleDetector uses OverlapSphere with angle, height and line-of-sight checks.

The mesh and the detector have separate shape parameters (width, height, angle, and so on). Keep them identical when you tune a prefab β€” a test checks this.

πŸš€ 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 and add a vision mesh component (for example VisionCircleMesh). Assign a MeshFilter, a MeshRenderer and a material (Assets/Resources/VisionCone/Vision_mat.mat).
  2. Add the matching detector (for example TargetCircleDetector) and assign Body (the transform that looks forward), Target Mask and Obstacle Mask.
  3. Set Obstacle Mask on the mesh as well, then press Create Mesh to preview it in the Scene view.
  4. Enable Is Show Debug to see rays and hits 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

Shared mesh settings (BaseVisionMesh): Obstacle Mask, Cone Material, Sort Order, Precision. Shared detector settings (BaseTargetDetector): Target Mask, Obstacle Mask, Body, Is Show Debug, Precision.

Shape Main parameters
Circle / Sector Vision Angle (up to 360Β°), Vision Range, Raycast Offset; detector also has Height Above / Height Below
Arrow Width, Height, Tilt Angle (βˆ’45…45Β°), Segments, Raycast Offset
Half Ellipse Width, Height, Center Offset, Pre Length, Length, Segments, Raycast Offset
Offset Triangle Width, Height, Center Offset, Segments, Raycast Offset
Square Width, Height, Segments, Raycast Offset
Rhombus Side Length, Angle Degrees (10…170Β°), Segments, Raycast Offset

πŸ—οΈ 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.SetBaseTargetDetector β†’ 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
β”‚   β”‚   β”œβ”€β”€ Visions/              # BaseVisionMesh + 6 shapes
β”‚   β”‚   β”œβ”€β”€ Detectors/            # BaseTargetDetector, RaycastTargetDetector + 6 shapes
β”‚   β”‚   β”œβ”€β”€ 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 + Vision_mat
β”‚   β”œβ”€β”€ 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 VisionMyShapeMesh : BaseVisionMesh and implement GenerateMesh(). Override ParamsChanged() / CacheParams() for your parameters.
  2. Create TargetMyShapeDetector : RaycastTargetDetector and implement RayOrigin, EdgePointCount and GetEdgePointWorld(i) with the same outline formula as the mesh.
  3. In the Editor, create a prefab with both components in Assets/Resources/VisionCone/.
  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
Create / Delete Mesh BaseVisionMesh inspector (Odin buttons) Build or remove the vision mesh in Edit Mode

πŸ§ͺ Tests

135 automated tests live in Assets/Tests:

Suite Count What it checks
EditMode (Tests.EditMode) 115 Prefab wiring and layer masks, mesh/detector parameter parity, mesh geometry (valid upward triangles, full shape, wall clipping, sector area), detector vs. drawn field (inside seen, outside ignored, walls block, nearest wins, events), Resources and scene integrity, Zenject bindings, HUD input parsing, save/load
PlayMode (Tests.PlayMode) 20 Boot β†’ Game, PlayLevel for every shape, level restart, the full demo path for every shape, PlayerMover, reloading Game while the weapon aims

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).

πŸ” 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