Skip to main content
Glama
unity-2d-topdown-lessons

unity-2d-topdown-lessons

README.md
# Unity 2D Top-Down Lesson & Architecture RAG (`unity-2d-topdown-lessons`)

Offline-ready Hybrid RAG + MCP Server distilled from proven Unity 2D top-down courses, official Unity technical articles, open-source companion C# repositories, and Unity 2022 LTS / Unity 6 LTS best practices.

Built so AI coding agents retrieve battle-tested game engineering patterns and pitfall fixes **before** writing C# scripts or configuring 2D scenes—eliminating guesswork, physics glitches, sorting bugs, and deprecated APIs.

## Researched Source Corpus (`raw_sources/`)

- **YouTube Playlists & Supercuts**: 9 playlists (`317` cataloged playlist entries in `raw_sources/youtube/playlists_index.json`), `112` extracted video transcripts + chapter maps (`~2.42M` chars across Game Code Library, Chris' Tutorials, Night Run Studio, Ketra Games, Sunny Valley Studio, Code Monkey, Brackeys, Mister Taft Creates, Digital Oddities/Sally, Terresquall, Unity GDC/Official).
- **Web Courses & Technical Articles**: `32` extracted guides (`raw_sources/web/`) from Unity Learn (`2D Tech Art Essentials`), Unity Happy Harvest technical series (`Tilemaps`, `URP 2D Lights`, `Unity 6 Character Animation`, `2D VFX & Shader Graph`), GameDevBeginner, Terresquall Vampire Survivors Parts 1–4 + 2.5, Madwomb, and NavMeshPlus.
- **Companion GitHub Repositories**: `12` shallow-cloned repositories (`raw_sources/github/`) including `h8man/NavMeshPlus`, `SunnyValleyStudio` (`ContextSteering`, `ProceduralDungeon`, `Tank2D`, `CleanerCode`), `MisterTaftCreates/Unity-Zelda-Like`, and `Brackeys` (`2D-Shooting`, `Health-Bar`, `2D-Shader-Graph`, `2D-Glow`, `2D-Lights`, `Minimap`).

## Curated Knowledge Base (`docs/`)

| File | `doc_id` | Coverage |
|---|---|---|
| `00_master_roadmap_and_architecture.md` | `master-roadmap-and-architecture` | Project folder setup, URP 2D, SO rules, Events, Execution Order, Unity 2022 vs Unity 6 matrix |
| `01_movement_input_and_physics2d.md` | `movement-input-and-physics2d` | Input System, `ClampMagnitude` diagonal fix, `linearVelocity`, corner snagging, Dash & Knockback gating |
| `02_tilemaps_sorting_camera_pixel_perfect.md` | `tilemaps-sorting-camera-pixel-perfect` | CompositeCollider2D, seam fixes, Custom Axis `(0,1,0)` Y-sorting, `SortingGroup`, PPU math, CM2/CM3 `Confiner2D` |
| `03_animation_and_visual_juice.md` | `animation-and-visual-juice` | 4-dir Blend Trees + `LastMove`, code `Animator.Play`, `SpriteLibrary`, Hit Flash, Hitstop, Mesh Particles, 2D Audio |
| `04_combat_projectiles_and_health.md` | `combat-projectiles-and-health` | `ScreenToWorldPoint` Z fix, `LayerMask` bitmasks, `markedEnemies`, `IDamageable`, I-Frames, `ObjectPool<T>` |
| `05_enemy_ai_and_2d_pathfinding.md` | `enemy-ai-and-2d-pathfinding` | Enemy FSM, LoS hysteresis, Sunny Valley Context Steering, `NavMeshPlus` 2D setup & caveats, Grid A* |
| `06_procedural_generation_worlds.md` | `procedural-generation-worlds` | Random Walk, Corridors-First, BSP Rooms, 4/8-bit Bitmask Walls, Infinite Viewport Chunk Streaming |
| `07_urp_2d_lighting_shaders_vfx.md` | `urp-2d-lighting-shaders-vfx` | `Light 2D` + `Sprites-Lit-Default`, Normal/Mask rim maps, Foot `ShadowCaster2D`, Negative Multiply shadows, Shader/VFX Graph |
| `08_rpg_systems_inventory_dialogue_quests_save.md` | `rpg-systems-inventory-dialogue-quests-save` | `IInteractable`, Inventory/Stack/Split, Dialogue Typewriter, Quests, Shops, Entrance Spawns, JSON Saves |
| `09_ai_agent_anti_patterns_and_qa_checklist.md` | `ai-agent-anti-patterns-and-qa-checklist` | 32 diagnostic bugs + Pre-Delivery QA Gate |
| `10_courses_and_lessons_compendium.md` | `courses-and-lessons-compendium` | Full curated map of tutorials, playlists, blogs & companion repos |

## Hybrid Retrieval & MCP Server Architecture

- **`ingest.py`**: Builds BOTH a normalized **SQLite FTS5** database (`data/lessons.sqlite3`, `unicode61 remove_diacritics 2`) with a structured `pitfalls` table AND a **ChromaDB** dense vector store (`data/chroma/`) using local cached `all-MiniLM-L6-v2` ONNX embeddings.
- **`lesson_rag.py`**: Lazily loads ChromaDB + local ONNX embeddings (so MCP `initialize` takes milliseconds), expands bilingual Vietnamese/English Unity queries, fuses FTS5 BM25 + semantic cosine ranks via **Reciprocal Rank Fusion (RRF)** with curated-tier weighting, and exposes 4 read-only MCP tools over stdio JSON-RPC 2.0:
  - `search_2d_lessons`
  - `read_2d_lesson`
  - `get_2d_pitfalls`
  - `list_2d_topics_and_courses`

## Quick Setup

```bash
git clone https://github.com/tuanvu17112003/unity-2d-topdown-lessons-mcp.git
cd unity-2d-topdown-lessons-mcp

# 1. Install runtime dependencies (ChromaDB + ONNX runtime)
pip install -r requirements.txt

# 2. (Optional) Re-download YouTube transcripts & companion GitHub repos into raw_sources/
# Requires yt-dlp and git
python fetch_sources.py

# 3. Build local SQLite FTS5 + ChromaDB ONNX index (downloads ~79 MB all-MiniLM-L6-v2 on first run)
python ingest.py

# 4. Check index statistics & run smoke tests
python lesson_rag.py stats
python smoke_test.py

# 5. Query from CLI (English or Vietnamese)
python lesson_rag.py search "tại sao nhân vật di chuyển chéo nhanh hơn và bị kẹt góc tường"
python lesson_rag.py pitfalls "NavMeshAgent sprite vanishes"
python lesson_rag.py read movement-input-and-physics2d
```

> **Note on repository size & third-party sources**: `data/` (generated SQLite + Chroma binaries) and `raw_sources/{github,web,youtube/videos}/` (~4.67 GB of third-party cloned repos, transcripts, and scraped blogs) are excluded via `.gitignore`. Only original synthesized Markdown guides (`docs/`), playlist metadata (`raw_sources/youtube/playlists_index.json`), and RAG server scripts are tracked in Git.

## MCP Registration (`mcp_config.json`)

```json
"unity-2d-topdown-lessons": {
  "type": "stdio",
  "command": "/path/to/python",
  "args": ["-B", "/path/to/unity-2d-topdown-lessons-mcp/lesson_rag.py", "mcp"],
  "env": {
    "PYTHONUTF8": "1",
    "ANONYMIZED_TELEMETRY": "False"
  },
  "timeoutMs": 120000
}
```

## Security & Privacy Design

- **Read-only SQLite URI mode**: `lesson_rag.py` opens `data/lessons.sqlite3` strictly via `?mode=ro`.
- **Zero filesystem path traversal**: `read_2d_lesson` reads solely from indexed `docs` rows in SQLite—never arbitrary host paths.
- **Parameterized queries**: All SQL & FTS5 inputs are parameterized or escaped; JSON-RPC handles malformed frames safely without crashing.
- **Offline inference**: No external API keys required at runtime.