How to Build a Single-File 3D Action Game with AI: A Complete Workflow
This article breaks down how a roughly 30MB single-file 3D action game can be produced with AI coding tools, covering the full pipeline from specification to packaging. It first explains why 3D action games cannot be generated in a single prompt, then walks through the asset pipeline (text-to-image, image-to-3D, retopology, PBR materials, animation, and voice-over), the code skeleton (render loop, input buffering, camera, and state management), data-driven combat state machines (combos, dodge, parry, executions, and boss phases), audio management, layered compression and single-file packaging, and runtime performance optimization. It closes with four-dimensional evaluation criteria and a reusable checklist for developers who want to treat AI as a reliable executor on this pipeline rather than expecting one-shot results.
1. Introduction: Why One HTML File Is Worth Dissecting
You click a single HTML file and drop into a 3D scene. An incense burner sits in the scene, and a few stone lanterns line the path. The character you control wields a long sword; press attack and the blade carves out a three-hit combo. Press block at the exact moment an enemy swings, and you trigger a parry, followed by an execution. A gourd is raised to the lips, and health slowly recovers. At last, the boss rises, delivers a second line of dialogue, and enters its second phase. All of this fits inside a single HTML file of roughly 30MB. The scene, models, textures, music, sound effects, and voice-over are all included, with no installation required.
Generating web applications with AI coding tools is no longer new, but this kind of project has three unusual characteristics:
- Assets are produced end-to-end by AI. The character and prop textures are generated by a text-to-image model, then converted into meshes by an image-to-3D model, while the program code assembles them into a game.
- The deliverable is a single file. Every binary asset is inlined into the same web file, which can be double-clicked to run or uploaded to any static hosting service for distribution.
- The completeness approaches a playable prototype. It has a full combat loop, consumables tied to character progression, and staged boss fights — not just a technical demo.
Dismissing it as a lucky result of “well-written prompts” misses the real value. It is better understood as a condensed sample of engineering practice, spanning procedural asset production, real-time rendering, animation and state machines, audio systems, and front-end asset packaging. The sections below work through it in the order of “why do it — how to do it — how to measure it,” extracting methods that can be reused.
2. Why These Games Are Hard to “Generate in One Prompt”
Gameplay that pure code can deliver — simple shooting or dodging mini-games with straightforward rules — can be generated in full and run directly within a single turn of conversation. 3D action games are different:
- Different asset dimension. The former is drawn from geometry, solid-color materials, and code-generated graphics. The latter depends on models, textures, animations, music, and voice-over, most of which are binary files that cannot be produced directly through conversation.
- Different iteration model. A single-file mini-game supports a fast “generate — run — fix” loop. A 3D game, even with all assets in place, needs repeated playtesting and tuning for combat feel, camera behavior, and numeric balance.
- Different context capacity. Every asset has size. Putting the full asset detail of 5 characters, 2 weapons, a dozen-plus scene props, and various drops into the conversation context quickly hits the ceiling of the model’s context window.
For this reason, such projects are inherently multi-stage collaborations: the model handles code generation and orchestrates the calls to asset-generation tools, while the developer defines specifications, accepts results, and safeguards game feel. A practical stage breakdown:
- Specification: the core gameplay loop, asset list, naming and parameter conventions;
- Engineering skeleton: scene and camera, input system, render loop, UI and game-state management;
- Asset production: style definition, text-to-image generation, image-to-3D, topology and texture processing, animation and audio;
- Integration: asset hookup, action state machines, combat hit detection, boss-fight flow;
- Performance and packaging: budget control, geometry/texture/audio compression, general compression and single-file packaging;
- Acceptance and tuning: compatibility, frame rate, game feel and numeric balance.
The stages do not flow in one direction only. For example, if the asset stage reveals excessively high polygon counts, you fall back to revise the asset spec; if the packaging stage finds the size over budget, you fall back to check texture resolution and audio bitrate. Designing good feedback loops matters more than expecting a single generation to get everything right.
3. Asset Pipeline: From Prompts to Renderable 3D Assets
The visual quality of a 3D action game depends mainly on whether the asset pipeline is stable.
Step one is to lock down the style. Letting the model write prompts automatically improves efficiency, but characters, weapons, and scene props must be constrained by the same set of style keywords — including shape features, materials (weathered bronze, eroded stone), color palette, lighting direction, and background requirements. Otherwise, each asset looks refined on its own but seems to come from a different game once placed in the same scene. For character parts that need to keep a consistent shape, generate a reference image first and use it as input for subsequent assets, so the parts of the same character stay visually coherent.
Step two is text-to-image. Two points deserve special attention here:
- Output on a transparent background, which makes later automatic background removal and texture use easier;
- Use “asset-style” output with even lighting, avoiding baking strong highlights and shadows into the texture. Otherwise, once the model moves to real-time lighting, “double shadows” appear.
Step three is image-to-3D. Most image-to-3D approaches start from a single image or multiple views, first reconstructing geometry and then generating textures. Raw output is often built for “looking good” rather than “running fast,” and using it directly for real-time rendering brings two kinds of problems:
- Irregular mesh topology and redundant polygon counts, leading to heavy draw calls and vertex overhead;
- Textures packed into a single large image that mixes color, lighting, and detail together, making real-time adjustment of parameters like specular and metalness difficult.
So a unified post-processing step is needed:
- Retopologize, reducing the polygon count to the target budget;
- Redo UV unwrapping, controlling texture utilization;
- When necessary, bake normal, roughness, and other maps from a high-poly model, then present them uniformly with a standard PBR material;
- Generate levels of detail (LOD) for distant objects.
Step four is to write the conventions into the asset manifest. The specification is defined by people at the start of the project, and the model follows it item by item while producing assets. In practice, the most common problem is not a single asset but inconsistency between assets. The following conventions are worth fixing in the manifest:
- Skeleton: all humanoid characters share the same skeleton, so the animation library only needs to be made once and can be reused;
- Units and orientation: uniformly use meters, +Y up, characters facing -Z, with the origin at the feet;
- Materials: all assets use the same PBR material profile, to allow batch rendering;
- Size: each asset specifies a texture resolution and polygon-count cap.
{"skeleton": "humanoid_v1","units": "meter","up_axis": "+Y","facing": "-Z","pivot": "feet","material_profile": "pbr_stylized_v1","assets": [{ "id": "char_hero", "kind": "character", "tris_max": 20000, "tex_max": "2K" },{ "id": "prop_censer", "kind": "prop", "tris_max": 3000, "tex_max": "1K" },{ "id": "prop_lantern", "kind": "prop", "tris_max": 2000, "tex_max": "1K" },{ "id": "prop_stele", "kind": "prop", "tris_max": 2500, "tex_max": "1K" },{ "id": "fx_drop_potion","kind": "pickup", "tris_max": 500, "tex_max": "512" }]}
Finally, animation and voice-over should also be treated as assets. A humanoid character’s attacks, dodges, and hit reactions can be derived through the shared skeleton via reuse, retargeting, and parameterized blending; a boss’s cutscene dialogue can be generated with speech synthesis and paired with subtitles. This way, experiences like “the character has moves” and “the boss has lines” no longer depend on heavy manual production, but on a unified asset spec.
4. Code Skeleton: Putting the Playable Loop Before the Assets
Asset production is asynchronous and time-consuming, but the engineering skeleton can run early. It is worth building the following modules first:
- Render loop: drive rendering with requestAnimationFrame and update logic on a fixed timestep. This keeps combat hit detection unaffected by frame-rate fluctuations and makes results reproducible.
- Input system: wrap keyboard, mouse, gamepad, and touch input behind a unified interface, and introduce input buffering. A dodge or the next combo hit pressed early during attack recovery is stored and fires the moment the action ends. This is one of the key details that makes the controls feel responsive.
- Camera: a third-person follow camera. When a target is locked, it smoothly turns toward the enemy; collision detection between the camera and scene obstacles prevents clipping through walls.
- Game state: use a finite state machine to manage the flow between “loading — title — combat — cutscene — results.”
- Placeholder assets: early on, use simple procedurally generated geometry as stand-ins for characters and props to validate controls and combat pacing; once real assets are ready, swap them in one by one without changing the logic.
When module boundaries are clean, the model’s code generation becomes far more stable. Rather than a vague request like “make a 3D action game,” it is better to break it into clearly scoped, independently verifiable tasks like “implement a character controller with input buffering” and “implement parry detection and the enemy stagger state.”
5. Combat and Actions: Data-Driven State Machines
The action system is the core of this kind of game, and also the part most prone to “looking right but feeling wrong.” A reliable approach is to define actions as data rather than scattered if-statements in code.
Each action can be described as a timeline:
- Startup: from trigger to when hit detection takes effect;
- Hit window: which frames produce attack hitboxes;
- Cancel points: from which frame the next action is allowed to chain;
- Recovery: the time from action end until control returns.
interface ActionClip {id: string;duration: number; // total action duration (seconds)hitStart?: number; // moment hit detection takes effecthitEnd?: number; // end of the hit windowcancelAt?: number; // moment the next action can cancel / chain innext?: string; // next action in the comboonEnter?: (ctx: CombatContext) => void;onEvent?: (name: string, ctx: CombatContext) => void; // e.g. "release_projectile"}
On this basis, each mechanic has its own design considerations:
- Three-hit combo: if the player keeps attacking after the first hit lands or reaches a cancel point, or if there is still buffered input at that point, chain to the next hit; if no input comes in time, return to idle. The three hits should escalate in displacement, damage multiplier, and recovery time, so the “hitting harder each time” feedback is clear.
- Dodge: brief invincibility frames plus displacement, consuming stamina, with a recovery period after the action. Invincibility should not cover the entire displacement, or dodging becomes a risk-free universal key.
- Block and parry: a normal block continuously reduces damage and consumes stamina, and running out of stamina breaks the guard; a parry only checks a short “perfect window,” and a success in that window zeroes damage and puts the enemy into a stagger.
- Execution and parry execution: when an enemy is staggered, get close and press the interact key to trigger an execution that plays a high-damage cinematic animation; a “parry execution” chains the stagger window after a successful parry directly into an execution, forming a seamless combo. The key to this design is “high reward corresponds to high-precision input,” and that is where the positive feedback comes from.
- Drinking potions and flying-sword moves: drinking a potion sets a cast time, slows movement, and can be interrupted by attacks; displacement or attack skills like the flying sword can reuse the normal action state machine, spawning effects and hit detection at specific frames through animation events.
- The ultimate “Ten Thousand Swords Return”: released once a charge resource is full, it can appear as multi-stage auto-targeting hit detection or a single full-screen area attack. Either way, implement it with “multiple short hit windows” rather than “one big hit window,” which makes combat feel easier to tune.
To keep these mechanics tunable, use “animation events” to decouple presentation from logic: the animator marks events on the animation timeline, and the code only listens for them. For example:
class HeroController {private state = "idle";private buffer: ActionClip[] = []; // input bufferprivate poise = 0; // character poiseupdate(dt: number) {this.tickTimers(dt);this.consumeBuffer();}private takeHit(atk: IncomingAttack, now: number): HitResult {// dodge invincibility framesif (this.isInvincible(now)) return HitResult.Dodged;// parry: only accept frontal attacks from the attacker within the "parry window"const facingEnemy = this.facesAttacker(atk.source);if (atk.parryable && facingEnemy && this.withinParryWindow(now)) {return HitResult.Parried; // the combat system staggers the attacker}// block: when facing the enemy, reduce damage by block direction and consume staminaif (facingEnemy && this.isGuarding) {return this.stamina > atk.guardCost? HitResult.Blocked: HitResult.GuardBroken;}// normal hit; enter stagger / knockdown when poise reaches zerothis.poise -= atk.poiseDamage;return this.poise <= 0 ? HitResult.Staggered : HitResult.Hit;}}// animation-event-driven two-part skillconst flyingSword: ActionClip = {id: "skill_flying_sword",duration: 1.2,onEnter: ({ rig, actor }) => rig.play("skill_flying_sword"),onEvent: (name, { scene, actor }) => {if (name === "release_sword") scene.spawnProjectile(actor, { speed: 18, damage: 35 });},};const bossPhase2: ActionClip = {id: "boss_phase_transition",duration: 3.5,onEnter: ({ rig, director }) => {director.playCutscene("boss_phase2_intro"); // cutscene + dialoguerig.play("boss_getup");},onEvent: (name, { boss }) => {if (name === "invincible_on") boss.setInvincible(true);if (name === "invincible_off") {boss.setInvincible(false);boss.phase = 2; // switch the move set and stats}},};
Boss fights can be further data-driven: phases are triggered by health thresholds, invincibility flags during cutscenes prevent players from “dealing damage during the cutscene,” dialogue and the get-up animation are aligned precisely via animation events, and the second phase switches the move set and aggression. The benefit is that tuning difficulty only changes data, not code.
On the numeric side, you also need a simple set of balancing rules. A parry window is typically measured in tens of milliseconds; too generous and combat loses tension, too strict and it drives new players away. A common approach is an “assist window”: use a precise window for the success check, but a slightly wider, more forgiving window for visual and audio feedback, so the player perceives it more naturally.
6. Audio and Voice-Over: An Underrated Lever for Size and Experience
Audio contributes enormously to immersion, yet it is also the part most easily overlooked in single-file size.
- Music: pick good loop points for BGM loops, and cross-fade on scene transitions to avoid abrupt cuts. Continuously playing background music takes up a large, hard-to-compress share of the size, so favor short loops suited to repetition and use sensible sample rates and bitrates.
- Sound effects: attack, hit, parry, and potion sounds should be layered — for example “swing + impact + metallic parry” playing at once. Slight pitch randomization on each playback reduces the sense of repetition. Positional sounds convey direction through panning or 3D spatial audio — low cost, with a clear boost in spatial feel.
- Voice-over: boss lines can be generated with speech synthesis, then denoised, loudness-normalized, and paired with subtitles. Store voice audio split by character and line, and fetch it on demand during cutscenes, which saves resources compared with decoding everything into memory up front.
- Playback management: load and play all audio through a unified audio manager, and reuse audio instances with an object pool to prevent the overhead of frequent creation and destruction.
7. Single-File Packaging: The Compression Engineering Behind 30MB
The idea that “one web file contains all assets” works because of a layered compression and packaging scheme.
Inlining approach. There are two common methods:
- Convert assets into a text encoding and embed it directly in the HTML;
- Assemble all binary assets into a custom container, with the HTML embedding only the container and an index table.
The latter avoids the extra bloat from text encoding and makes it easier to read assets on demand at runtime.
Layered compression, from highest to lowest payoff:
- Textures. Textures are usually the biggest contributor to size. Beyond lowering resolution, the more important step is switching to a GPU-sampleable format: after download, assets can be uploaded straight to the GPU without being decompressed into memory, saving both VRAM and decode time. Pairing this with a material atlas that packs many small textures into one large image further reduces the number of asset files.
- Geometry. Retopology reduces triangles; merging vertices and quantizing coordinate precision, combined with general geometry compression, can often cut static scene asset size dramatically.
- Audio. Use a lower-bitrate lossy codec for music; unify the sample rate of the many short sound effects and trim silent segments; lower the sample rate of voice audio where appropriate. Human ears are often insensitive to these adjustments, but the size savings are direct.
- General compression. Run a lossless compression pass over the whole package — for example with a general-purpose algorithm like DEFLATE or zstandard. For already-compressed data like models and textures the gains are limited, but for code and JSON indexes they remain substantial.
- On-demand loading. Split assets into a “core pack + optional packs,” deferring non-essential voice or localization assets, so first-screen size drops accordingly.
const RESOURCE_PACK = "U2FsdGVkX1..."; // asset pack compressed with a general-purpose algorithm and embedded as text// 1) decode to a byte streamconst packed = Uint8Array.from(atob(RESOURCE_PACK), c => c.charCodeAt(0));// 2) compression happened at build time, so runtime only needs to decompress (prefer running in a Worker thread to avoid blocking rendering)async function unpack(bytes) {const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("deflate-raw"));return new Uint8Array(await new Response(stream).arrayBuffer());}// 3) locate and read a single asset by its index tablefunction buildIndex(buf) {const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);const count = view.getUint32(0, true);const index = new Map();for (let i = 0; i < count; i++) {const base = 4 + i * 24;const id = new TextDecoder().decode(buf.subarray(base, base + 16)).replace(/\0+$/, "");index.set(id, { offset: view.getUint32(base + 16, true), length: view.getUint32(base + 20, true) });}return (id) => buf.subarray(index.get(id).offset, index.get(id).offset + index.get(id).length);}
Engineering details make or break it.
- Index table first. Asset IDs, offsets, and lengths are written into an index table at build time, and read by ID at runtime. This lets the same game code adapt to different batches of asset packs.
- Compression vs. decompression trade-off. Algorithms like zstandard typically offer higher compression ratios and faster decompression, well suited to “compress once at build time, decompress repeatedly at runtime.”
- Progressive loading. Showing progress across the decode, decompress, and GPU-upload stages gives a far better experience than a single progress bar that sits still for a long time.
The build script can be automated further. You can have the model generate the packaging script from the asset manifest, checking at build time whether assets meet spec (polygon count, texture size, naming, skeleton consistency), and automatically handle compression, packaging, and self-checks.
// scripts/build-pack.mjs (illustrative)import { readFile } from "node:fs/promises";import zlib from "node:zlib";import { packResources } from "./pack-lib.mjs";const manifest = JSON.parse(await readFile("assets/manifest.json", "utf8"));for (const spec of manifest.assets) {const meta = JSON.parse(await readFile(`assets/${spec.id}.meta.json`, "utf8"));if (meta.tris > spec.tris_max) {throw new Error(`${spec.id}: tris ${meta.tris} exceeds budget ${spec.tris_max}`);}}const { buffer, index } = await packResources(manifest); // concatenate + build the index tableconst compressed = zlib.deflateRawSync(Buffer.concat([index, buffer]));await writeFile("src/resource-pack.js",`export const RESOURCE_PACK = "${compressed.toString("base64")}";\n`);const kb = (compressed.length / 1024).toFixed(1);console.log(`Resource pack generated: ${kb} KB, ${manifest.assets.length} assets in total`);
Once asset size is back within budget, you still need to maintain an asset budget table and set a size-change threshold alert in the CI pipeline, to prevent size from quietly creeping back up during later iterations.
8. Runtime Performance and Compatibility
Assets fitting in the file does not mean the game runs well. Common real-time rendering optimizations include:
- Batching and instancing: static scene props with the same material can be batched or instanced to cut draw calls; props like stone lanterns and steles that get placed in large numbers are especially suited to this;
- LOD and culling: switch model detail by camera distance and apply frustum culling so off-screen objects are not rendered;
- Simplified collision: use simple shapes like capsules and boxes for complex models in physics calculations;
- Memory management: use object pools for high-frequency objects like bullets, particles, and damage numbers to avoid garbage-collection stutter from frequent allocation;
- Shader precompilation: compiling shaders when a new material first appears causes hitches; warm them up during the loading stage.
On compatibility, differences between desktop and mobile browsers show up mainly in VRAM limits, decoding capability, and touch controls. The touch version needs a virtual joystick and button layout; low-end devices should automatically lower render resolution and effects level, with adaptive quality tiers.
Distribution is worth attention too. The single-file form is well suited to static hosting: you can upload it to object storage and distribute it via a CDN, or share it directly for local opening. If you want to play directly in the browser through a link, note the browser security restrictions on file:// pages — use static hosting rather than opening the file locally.
9. How to Evaluate the Result: From “Runs” to “Playable”
Whether an AI-generated 3D action prototype is acceptable can be measured on four dimensions:
- Functional completeness: whether the core loop closes, including combat, death and revival, and staged boss fights;
- Asset consistency: whether the style is unified, whether specs match the manifest, and whether naming is standardized;
- Performance stability: whether frame rate holds steady on the target device, and whether there is loading stutter or continuously growing memory;
- Game feel and balance: whether input is responsive, whether the parry window is reasonable, and whether the difficulty curve is smooth.
These products still fall well short of complete commercial works. Commercial games have mature workflows supporting animation layering and transitions, physics interaction, enemy AI behavior trees, level editing, multi-platform adaptation, and long-term stability. Still, as a “vertical slice” — a playable segment that implements only the core gameplay — it can already validate a gameplay idea, showcase an art direction, and serve as technical research.
The original case also illustrates the capability boundary: a shooting mini-game drawn entirely with code can be generated in a single turn of conversation, while a game that needs models, textures, and voice-over must go through a multi-stage pipeline and cannot be done in one step today. Understanding this boundary is what lets you arrange the division of labor between people and models sensibly.
10. A Reusable Practice Checklist
- Set specs before generating: write the style keywords, skeleton, unit/orientation, material profile, asset naming, and budget into a manifest early in the project;
- Break into small modules before handing to the model: generate and verify controllers, combat detection, camera, and audio management one at a time;
- Unify asset post-processing: retopology, redo UVs, bake maps, unify the PBR material, generate LODs;
- Data-drive actions: put frame windows, cancel points, and animation events into data config, and use object pools and a fixed timestep to ensure performance and consistency;
- Manage audio in layers: compress music, sound effects, and voice by category, with a unified audio manager and object pool;
- Compress in layers: handle textures, geometry, audio, general compression, and on-demand loading in turn, and monitor size in CI;
- Set acceptance criteria: define “done” by the four dimensions of function, consistency, performance, and feel, rather than relying on subjective judgment.
11. Conclusion
A roughly 30MB single-file 3D action game appears, on the surface, to show progress in the model’s “generation ability,” but in essence it combines mature engineering methods: asset pipelines, real-time rendering, animation state machines, and front-end packaging. The value of AI lies in connecting these stages together and dramatically compressing the path from idea to playable prototype; the value of people lies in defining specs, safeguarding quality, and tuning feel — in deciding the ceiling of the experience. For developers, rather than asking “can a model make a 3D game in one shot,” it is better to break requirements into verifiable small steps, set clear specs and budgets for assets, and let AI act as a reliably running executor on this pipeline.
