<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Thinking in AI, Philosophy, Investing, and Mind on Medium]]></title>
        <description><![CDATA[Stories by Thinking in AI, Philosophy, Investing, and Mind on Medium]]></description>
        <link>https://medium.com/@augustdeepthink?source=rss-310dfdf9c269------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0BvLL-8MrswfdLGo5V1Iow.jpeg</url>
            <title>Stories by Thinking in AI, Philosophy, Investing, and Mind on Medium</title>
            <link>https://medium.com/@augustdeepthink?source=rss-310dfdf9c269------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 18:31:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@augustdeepthink/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building StarCraftZero from Scratch — Part 11: Lots of new features (v0.6.5)]]></title>
            <link>https://augustdeepthink.medium.com/building-starcraftzero-from-scratch-part-11-lots-of-new-features-v0-6-5-5804154af22a?source=rss-310dfdf9c269------2</link>
            <guid isPermaLink="false">https://medium.com/p/5804154af22a</guid>
            <category><![CDATA[starcraft]]></category>
            <dc:creator><![CDATA[Thinking in AI, Philosophy, Investing, and Mind]]></dc:creator>
            <pubDate>Thu, 19 Mar 2026 00:51:06 GMT</pubDate>
            <atom:updated>2026-03-19T01:39:58.048Z</atom:updated>
            <content:encoded><![CDATA[<p><em>March 16–18, 2026</em></p><p>Big update on the StarCraftZero. Gone from v0.4.4 to v0.6.5. Here’s what’s new:</p><p><strong>New Buildings:</strong></p><ul><li>Bunker — garrison up to 4 infantry, they fire from inside using their own weapons (+1 range bonus). Right-click to load, click icons to eject individual units</li><li>Missile Turret — dedicated anti-air, twin missiles, requires Engineering Bay</li><li>Sensor Tower — 22-tile radar range, reveals enemy positions on minimap through fog</li></ul><p><strong>Death Effects &amp; Combat Visuals:</strong></p><ul><li>Units explode on death with flash + debris scatter instead of just vanishing</li><li>Projectiles now leave stretched glowing trails</li><li>Impact flashes at hit points, splash rings show Siege Tank blast radius</li><li>Air units cast ground shadows for better readability</li></ul><p><strong>Minimap Overhaul:</strong></p><ul><li>Terrain cached as image texture (was 9,216 draw_rect calls per frame…)</li><li>Each unit type has a unique minimap color (Marine=blue, Medic=white, Tank=olive, etc.)</li><li>Building footprints render at actual size</li><li>Red expanding ring alerts when your units are under attack</li></ul><p><strong>Control Groups &amp; Selection:</strong></p><ul><li>Double-tap control group to snap camera to those units</li><li>Box-selecting over units + buildings only grabs units (SC2 behavior)</li><li>Multi-select wireframe grid in info panel with per-unit HP bars</li></ul><p><strong>Audio:</strong></p><ul><li>Positional audio — combat sounds fade as you pan camera away</li><li>Building select sounds, per-unit voice lines</li><li>Command voices interrupt selection voices (matches SC2 exactly)</li></ul><p><strong>Idle Animations:</strong></p><ul><li>Bio units breathe (subtle scale pulse + body roll)</li><li>All units do periodic fidget looks with per-unit angles (Marines scan alert, Medics look for wounded, Tanks barely move)</li><li>Mechanical units skip breathing but still fidget</li></ul><p><strong>Bunker QoL:</strong></p><ul><li>Walk-to-load: right-click bunker, units approach nearest edge</li><li>Full bunker = units stand guard outside</li><li>Garrison display with colored HP bar icons, click to eject</li></ul><p><strong>SC2 Fidelity Pass:</strong></p><ul><li>AI now builds full tech tree (Factory, Starport, Engineering Bay, Armory)</li><li>Building collapse animations (tilt + smoke + fade)</li><li>Fog of war hides enemy building HP bars</li><li>Overkill prevention — first lethal hit wins, other attackers re-target</li><li>13 movement bugs fixed (attack-move freeze, Viking a-move, air unit arrival jitter, repath counter accumulation)</li></ul><p><strong>QoL:</strong></p><ul><li>Game speed toggle (F10): Normal 1.0x ↔ Faster 1.4x</li><li>Perspective camera mode (F7)</li><li>Day/night cycle (F8)</li><li>HP bars scale with camera zoom</li><li>Info panel shows damage, armor, range, cooldown, supply</li></ul><p>This is the biggest polish update yet. Four separate passes — death animations, control group workflow, a minimap rewrite, and a full SC2 balance audit — all landing in a single devlog. The game hasn’t gained new unit types, but it <em>feels</em> dramatically different to play. Units explode when they die instead of vanishing. Bullets leave glowing trails. The minimap flashes red when your base is under attack. And you can finally double-tap a control group to snap the camera across the map. These are the details that separate a tech demo from something that actually feels like StarCraft.</p><h3>Phase 20: Death Effects &amp; Combat Visuals</h3><p>Before this update, units simply disappeared when they reached 0 HP. One frame they existed, the next frame — gone. It was technically correct but visually jarring. In StarCraft II, every death is a small event: an explosion, flying debris, a brief flash of light. These micro-moments of feedback are what make combat feel <strong>impactful</strong> rather than abstract.</p><h3>Death Explosions</h3><p>When a unit dies, the game now spawns a standalone Node3D effect at the death position (decoupled from the dying unit, which is immediately freed). The effect has two components:</p><ul><li><strong>Flash sphere</strong> — a bright orange-white sphere that expands rapidly and fades over 0.3 seconds, using emission energy for that overexposed “bloom” look</li><li><strong>Debris chunks</strong> — small box meshes launched outward with random velocity vectors, rotating as they fly, fading to transparent before being freed</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*9GHN0u9ZMr56O8SJVIRbfw.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*sk6XtNsezgBxoNvsxtiN2w.gif" /></figure><p>All animations use Godot’s Tween system rather than runtime GDScript logic. This was a deliberate choice — tweens are fire-and-forget, can&#39;t leak state, and don&#39;t require the effect node to run per-frame code. The effect spawns, the tweens play, and when the last tween finishes, the node frees itself.</p><h3>Projectile Trails</h3><p>Bullets were previously just small glowing spheres — easy to lose track of during a firefight. Now every projectile leaves a <strong>stretched cylinder trail</strong> behind it as it flies, oriented along the bullet’s movement direction. The trail uses the same emission color as the bullet itself but at reduced opacity, creating a comet-tail effect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*XaGcX8YM1uew1O4rJd8xDQ.gif" /></figure><p>The trail orientation updates every frame using look_at() along the movement vector, then rotating 90 degrees around the local X axis (because Godot&#39;s CylinderMesh is oriented vertically by default). This means trails correctly follow curved or arcing paths if we ever add them.</p><h3>Impact Flashes</h3><p>When a bullet reaches its target, it now spawns an <strong>impact flash</strong> — an expanding sphere of light at the hit point that fades over 0.3 seconds. For normal bullets, the flash matches the projectile color. For splash damage (Siege Tank shells), the flash is larger and orange, and is accompanied by a <strong>ground ring</strong> — a torus mesh showing the blast radius, which also expands and fades.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*QpssRxSEatRUWSWPzIGUQQ.gif" /></figure><p>The splash ring is particularly satisfying. When a Siege Tank fires in siege mode, you can see the shell travel across the map, hit the ground, and then a bright orange ring radiates outward showing exactly which units were in the blast zone. It communicates splash radius without any UI overlay.</p><p><strong>Design principle:</strong> Every visual effect serves a gameplay communication purpose. Death explosions confirm kills. Trails make projectiles trackable. Impact flashes show where damage landed. Splash rings show blast radius. Nothing is purely decorative.</p><h3>Air Unit Ground Shadows</h3><p>Flying units (Medivacs and Vikings in fighter mode) now cast a <strong>dark circle shadow</strong> on the ground beneath them. This is not engine shadow mapping — it’s a flat cylinder mesh at Y=0.01 with top_level = true so it stays at ground level regardless of the unit&#39;s altitude.</p><p>The shadow solves a real readability problem: in an orthographic view, it’s hard to judge whether a Medivac is directly over a group of Marines or ten tiles away. The ground shadow anchors the air unit’s position to the terrain. The selection ring also projects to ground level for the same reason — you can see exactly which tile an air unit occupies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*ZBPANBFGV1HVFRMnGHSGVA.gif" /></figure><p>Viking shadows automatically hide when the unit lands (ground mode) and reappear on takeoff, and the shadow mesh is excluded from the silhouette occlude pass so it doesn’t create ghost outlines behind buildings.</p><h3>Phase 21: Control Groups &amp; Selection QoL</h3><p>Control groups existed before this update — Ctrl+1 to assign, 1 to recall — but they were bare-bones. The missing piece was <strong>double-tap to center camera</strong>, which is such a fundamental SC2 workflow that its absence made the game feel clunky. You’d recall a control group, then manually pan across the map to find where those units actually were.</p><h3>Double-Tap Camera Snap</h3><p>Now, pressing a control group key twice within 0.4 seconds snaps the camera to the group’s center position. The implementation tracks the last recalled group number and timestamp:</p><pre>var _last_recall_group: int = -1<br>var _last_recall_time: float = 0.0<br>const DOUBLE_TAP_WINDOW: float = 0.4  # seconds</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*QZxa7eCj7d7DmVJggzq8NA.gif" /></figure><p>On recall, if the same group was recalled within the window, the camera jumps to the average world_pos of all units in the group (or tile_center_world for buildings). The double-tap state resets after a jump so you don&#39;t accidentally triple-tap and re-jump.</p><p>This single feature transformed gameplay flow. You can now set up control group 1 for your army, group 2 for your production buildings, and rapidly switch context: tap 1 to select the army, double-tap 2 to jump to your base and queue production, double-tap 1 to jump back to the front line. It’s the fundamental SC2 macro cycle.</p><h3>Voice Line Fixes</h3><p>Two subtle audio bugs were fixed in this phase:</p><ul><li><strong>Selection voices cutting off</strong> — rapidly clicking between units would interrupt voice lines mid-syllable. Now selection voices use a non-interrupting mode where a new selection voice only plays if the channel is free</li><li><strong>Command voices force-interrupt</strong> — move and attack commands <em>should</em> cut off selection voices (in SC2, issuing a command immediately plays the acknowledgement). Command voices now force-interrupt any playing voice line</li></ul><p>The distinction is subtle but matches SC2’s exact behavior: clicking around your units lets their voice lines finish naturally, but issuing a command immediately plays “Yes, sir!” or “Move out!” over anything in progress.</p><h3>Building Selection Sounds</h3><p>Buildings were silent when clicked — no feedback at all. Now selecting a building plays a mechanical bunker sound, and Medivacs got their own dedicated selection voice instead of reusing the Marine voice. Small details, but they add up to making every interaction feel responsive.</p><h3>Minimap Overhaul</h3><p>The minimap was one of the oldest systems in the codebase, written back in Phase 6 when the game was still 2D. It worked, but it was doing something horrifying every single frame: <strong>9,216 individual </strong><strong>draw_rect() calls</strong> to render the 96x96 terrain grid. Every frame. At 60fps. That&#39;s over half a million draw calls per second just for the minimap background.</p><h3>Terrain Caching</h3><p>The fix was to cache the terrain as an Image/ImageTexture and only rebuild it when fog of war changes. The terrain image is a 96x96 pixel texture where each pixel represents one tile, colored by terrain type and fog state. Instead of 9,216 draw calls per frame, the minimap now draws a single textured rectangle and rebuilds the cache at 10Hz (or when explicitly marked dirty).</p><p><strong>Performance note:</strong> The terrain rebuild was also moved from _draw() to _process(). Godot&#39;s _draw() runs on the rendering thread, and doing heavy Image manipulation there was blocking the renderer. Moving it to _process() keeps the work on the main thread where it belongs.</p><h3>Accurate Building Footprints</h3><p>Buildings on the minimap previously rendered as single-pixel dots regardless of their actual size. A 3x3 Starport looked the same as a 1x1 Supply Depot. Now buildings use their actual footprint dimensions on the minimap — a Barracks occupies a 2x2 area, a Starport fills 3x3. AI buildings also properly respect fog of war visibility, only appearing when the player has vision.</p><h3>Unit Type Colors</h3><p>All units were the same green dot on the minimap. Now each unit type has a unique color that matches its in-game visual identity:</p><h4>Player Units</h4><p>Marine (blue), Marauder (purple), Medic (white), SCV (yellow), Siege Tank (olive), Medivac (teal), Viking (cyan)</p><h4>Enemy Units</h4><p>All enemy units render in red, matching SC2’s convention. Enemy buildings only visible when in fog-of-war VISIBLE state.</p><p>At a glance, you can now tell the composition of your army on the minimap — a cluster of blue and purple dots means infantry, teal dots trailing behind are Medivacs, olive near the front line means Siege Tanks are set up.</p><h3>Attack Alert Pings</h3><p>The most impactful minimap addition: <strong>red expanding ring alerts</strong> when your units take damage. In SC2, the minimap flashes when you’re being attacked, drawing your attention to threats you might not be watching. This is critical for macro play — you need to know when your expansion is being raided or your army is engaging without having the camera pointed there.</p><p>The implementation adds a was_attacked signal to UnitBase, emitted in take_damage() for player units (faction 0). The minimap listens for these signals and spawns animated red rings that expand outward and fade over about 0.7 seconds.</p><p>Two important safeguards prevent the minimap from becoming a Christmas tree during large battles:</p><ul><li><strong>Merge distance</strong> — pings within 3 tiles of an existing ping are merged rather than creating a new one, so a group of Marines under fire produces one ping, not twelve</li><li><strong>Ping cap</strong> — maximum 20 simultaneous pings, preventing performance issues in massive engagements</li></ul><h3>Phase 22: Info Panel &amp; Balance Pass</h3><h3>Multi-Select Wireframe Grid</h3><p>Selecting multiple units now shows a <strong>wireframe grid</strong> in the info panel — an 8x3 grid of colored rectangles, each representing one selected unit. The color matches the unit type (same palette as the minimap colors), and each icon has a tiny HP bar underneath showing that unit’s current health.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*24DRJGd34iM2SqrAt-EHqw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S99sHiQYscHQfjL73Q-yxA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e4Exm08TpDMOvOiy8JoOkA.png" /></figure><p>This is a wireframe implementation — placeholder geometry, no portraits or unit art. But the layout matches SC2’s multi-select panel, and it already communicates the essential information: how many of each type you have selected, and which ones are hurt.</p><h3>Single-Select Detail View</h3><p>Selecting a single unit now shows expanded stats: supply cost, current damage with upgrade bonuses displayed as +N, armor values, and attack cooldown. The portrait color uses a shared helper function, eliminating the duplicated color logic that had crept into multiple places.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yaAi-uBVJSWo2a0iC6dGOw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qsa7epuN0H71uE-xNR7Slw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*caWbo9V-8ZuZRnZJLm6Caw.png" /></figure><h3>SC2 Balance Audit</h3><p>A thorough pass through SC2 Liquipedia values caught several inaccuracies that had accumulated over the phases:</p><h4>Economy Fixes</h4><p>Factory now requires 100 gas (was free). Armory requires 50 gas (was free). These missing gas costs meant tech was far too cheap.</p><h4>Viking Fighter Mode</h4><p>Damage corrected from 10 to 20 (two missiles at 10 each), bonus vs armored from +4 to +8, and upgrade scaling set to x2 per level.</p><h4>Medic Adjustments</h4><p>Speed reduced from 3.15 to 2.25 (Medics are slower than Marines in SC2). Base armor increased from 0 to 1.</p><h4>Upgrade Cost Split</h4><p>Infantry upgrades at Engineering Bay now have their own cost curve (L2: 150, L3: 200) separate from vehicle upgrades at the Armory, matching SC2’s independent upgrade paths.</p><p>Several other small corrections: Refinery build time adjusted from 21.4 to 21.0 seconds, SCV attack range from 0.5 to 0.2 tiles, and Medic gas cost from 25 to 50.</p><h3>Bug Fixes</h3><p>The balance pass surfaced several dormant bugs in the command card and minimap:</p><ul><li><strong>Command card crash</strong> — _dim_cmd_slot() was accessing a &quot;label&quot; key that had been renamed to &quot;desc&quot;, causing a crash when trying to grey out unavailable actions</li><li><strong>Stuck grey slots</strong> — _clear_cmd_slots() never reset the modulate property, so command card slots would stay permanently greyed out after being dimmed once</li><li><strong>Dead Attack Move button</strong> — the Attack Move command card button had no matching case in the click handler, making it keyboard-only. Now both hotkey and click work</li></ul><h3>Phase 24: Bunker, Missile Turret &amp; Sensor Tower</h3><p>The first static defense structures arrived in a single commit. Three buildings, each with a distinct role — but the Bunker was by far the most complex addition to date.</p><h3>The Bunker</h3><p>The SC2 Bunker is deceptively complicated. It’s not just a building with HP — it’s a <strong>container that fights using its passengers</strong>. Up to 4 infantry units can garrison inside. While garrisoned, each unit attacks independently using its own weapon stats, range (with a +1 bonus), and cooldown. The Bunker itself has no weapon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*1B9HNowczOd2ydukOHK53A.gif" /></figure><p>The garrison system required careful state management. Loading a unit sets visible = false, set_process(false), and set_physics_process(false) — the unit becomes inert but stays in the scene tree. An _attack_timers array tracks individual cooldowns per garrisoned unit. Each frame, the Bunker iterates its garrison, finds enemy targets using the shared scan_enemy_in_range() helper from BuildingBase, and fires bullets from the building&#39;s position on behalf of each unit.</p><p>Unloading uses a directional offset system — units emerge at 8 positions around the footprint (the 4 edges and 4 corners), with each subsequent unit taking the next available walkable slot. A spiral search fallback handles the case where the Bunker is built against a wall.</p><h3>Missile Turret &amp; Sensor Tower</h3><p>The Missile Turret is simpler — a dedicated anti-air building that fires twin missiles (12 damage × 2) every 0.61 seconds. It shares the same scan_enemy_in_range() helper as the Bunker, filtering for air-only targets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D5bew2kPeFQ16rXqwA7n2w.png" /></figure><p>The Sensor Tower has no attack capability at all. Its value is purely informational — a large radar range (22 tiles) that reveals enemy unit positions on the minimap as red blips, even through fog of war. The radar ping rendering uses concentric rings that expand outward, giving a satisfying “sonar sweep” effect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*fgMmMqg7C7Hb3f8nAFyTDA.gif" /></figure><p><strong>Code health note:</strong> All three buildings were an opportunity to extract shared patterns. The enemy-scanning loop was duplicated across unit_base.gd, bunker.gd, and missile_turret.gd — three separate implementations of the same logic. We extracted it into a single scan_enemy_in_range() method on BuildingBase, and the Bunker&#39;s duplicated take_damage() formula was replaced with a super.take_damage() call plus garrison-kill logic.</p><h3>Phase 25: Positional Audio &amp; Perspective Camera</h3><p>In real SC2, panning your camera away from a battle makes the combat sounds fade. Alerts and UI sounds remain at full volume. This distinction — <strong>world sounds vs. global sounds</strong> — is what makes the audio feel spatial.</p><h3>The play_at() System</h3><p>We added a new play_at(sound_name, world_pos) method to SoundManager. It computes the 2D tile-space distance from the sound source to the camera&#39;s focus point, applies a sqrt attenuation curve over a 22-tile range, and skips the sound entirely if it&#39;s beyond range (saving polyphony slots). Fifteen call sites across all combat units were migrated from play() to play_at().</p><pre>func play_at(sound_name: String, source_world_pos: Vector2, volume_db: float = 0.0) -&gt; void:<br>    var cam_pos: Vector2 = _cam.get_focus_world()<br>    var dist: float = source_world_pos.distance_to(cam_pos)<br>    if dist &gt;= POSITIONAL_RANGE:<br>        return   # silent — save polyphony slot<br>    var atten: float = sqrt(1.0 - dist / POSITIONAL_RANGE)<br>    play(sound_name, volume_db + linear_to_db(atten))</pre><p>We deliberately did <strong>not</strong> use Godot’s AudioStreamPlayer3D. The camera is orthographic at 80 units above the action — 3D audio would produce wrong panning based on that elevated listener position. The &quot;positional&quot; effect in SC2 is purely volume attenuation based on camera-to-source distance in tile-space, not physical 3D spatialization.</p><h3>Perspective Camera Fixes</h3><p>The perspective camera mode had several issues when zoomed out: pan speed was wrong (using ortho size instead of actual world coverage from dist × tan(fov/2)), the camera could scroll past map edges, and switching between ortho and perspective caused jarring view jumps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XfUuSjXMAg7Tup_hRWGQOA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R7IvLlqFY-QcprpzMOz9hQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N6plpqbcYKQ80dJrX1D5xQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oI-QqWAu1OTB-TA3AGQxIw.png" /></figure><p>The fix: derive perspective distance directly from the zoom level and FOV so the visible ground area always matches ortho at the same zoom. Two extracted helpers — _persp_dist_for_fov() and _half_world_view() — now serve pan speed, map clamping, and the mode-switch snap, eliminating the repeated formula.</p><h3>Phase 26: Idle Animations &amp; Unit Personality</h3><p>This was the phase where units stopped being static geometry and started feeling <strong>alive</strong>. In SC2, idle units breathe, shift their weight, and occasionally look around. These micro-animations communicate “this unit is awake and ready” even when nothing is happening.</p><h3>Procedural Breathing</h3><p>Every biological unit (Marine, Marauder, Medic, SCV) now has a subtle breathing animation — a low-frequency scale pulse on X/Z axes (1.5% amplitude, ~4-second cycle) combined with a slight body roll (~1 degree, ~7-second cycle). Each unit gets a random phase offset at spawn so a group of Marines doesn’t breathe in perfect sync.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*XXvimZXt5iKqVXue34CflA.gif" /></figure><p>Mechanical units (Siege Tank, Medivac, Viking) skip the breathing entirely — tanks don’t breathe. But they still do the fidget look.</p><h3>The Fidget System</h3><p>Every few seconds, an idle unit turns its head (body, really — these are placeholder boxes) a random amount on the Y axis, holds the position briefly, then turns back. The fidget timing and angles are <strong>per-unit</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*KlJHn2Q_OgzxJemu8O1K3w.gif" /></figure><h4>Bio Units</h4><p>Marine: 12–30° (alert soldier). Medic: 15–35° (scanning for wounded). SCV: 15–40° (busy worker). Marauder: 10–20° (heavy armor, slower turns).</p><h4>Mechanical Units</h4><p>Siege Tank: 5–10° (turret micro-adjust). Viking: 7–15° (aircraft scanning). Medivac: 5–12° (hover drift).</p><p>The first fidget after arriving at a new location triggers quickly (1–3 seconds) so units feel responsive. Subsequent fidgets use longer intervals (4–10 seconds) so the behavior feels natural rather than twitchy.</p><h3>SC2 Selection Priority</h3><p>A long-standing annoyance was fixed: box-selecting over a mix of units and buildings now <strong>only selects the units</strong>. Buildings are filtered out unless the box contains zero units (in which case all buildings in the box are selected). This matches SC2 exactly — your army control is never contaminated by accidentally grabbing a Supply Depot.</p><h3>Bunker Quality of Life</h3><p>The Bunker got a complete interaction overhaul:</p><ul><li><strong>Walk-to-load</strong> — right-clicking a Bunker makes units walk toward the nearest edge and load automatically on proximity (1.5 tiles). No fixed “entrance” — units approach from whatever side they’re closest to</li><li><strong>Full bunker = stand beside</strong> — if the Bunker is at capacity, right-clicking it still moves your units there. They stand guard outside instead of doing nothing</li><li><strong>Garrison display</strong> — selecting a Bunker shows colored unit icons with HP bars in the info panel. Left-click an icon to eject that specific unit</li><li><strong>Fire sounds</strong> — garrisoned units now play their weapon sounds at the Bunker’s position via the positional audio system</li></ul><h3>Info Panel &amp; Build Menu Polish</h3><p>Every portrait (both single-select and multi-select wireframe) now shows a <strong>centered abbreviation</strong> — “Mrn” for Marine, “Mdc” for Medic, “BRX” for Barracks, etc. Portrait colors match the actual mesh body colors. Clicking a portrait plays the unit’s select voice and centers the camera.</p><p>The SCV build menu expanded from 2×5 (10 slots) to 3×4 (12 slots) to accommodate all structures including the new Command Center buildable. Buildings are grouped logically: economy in column 1, military in column 2, tech and defense in column 3.</p><h3>Code Review Pass: 10 Bug Fixes &amp; Class Hierarchy Cleanup</h3><p>Between phase work, we ran a full 3-agent parallel code review across all 40 GDScript files — one agent for correctness, one for code quality, and one for CLAUDE.md convention compliance. The results were sobering: <strong>10 confirmed bugs</strong>, several of which had been silently degrading gameplay for multiple commits.</p><h3>Overkill Prevention Gaps (Rule 19)</h3><p>The _dying flag — set on the first lethal hit to prevent multiple units from wasting shots on the same target — had two blind spots. BuildingBase.scan_enemy_in_range() checked hp &lt;= 0 but not _dying, so Bunkers and Missile Turrets would occasionally waste an attack cycle on an already-dead unit. Similarly, _forced_target (the focus-fire target) was cleared only on hp &lt;= 0, not on _dying. Both were one-line fixes.</p><h3>Movement System: Three Hidden Bugs</h3><p>The most impactful fixes were in the movement system — bugs that had been present since the 3D conversion but only manifested under specific conditions:</p><ul><li><strong>Attack-move freeze at kill site</strong> — when an attack-moving unit killed its target mid-chase, it would arrive at the corpse location and stop permanently. The _resume_attack_move() call was guarded by not _moving, which was false during the chase, and by the time the unit stopped, no code path re-triggered the resume. Units in a-move waves would progressively freeze at each kill position across the map.</li><li><strong>Viking fighter attack-move did nothing</strong> — attack_move_to() set _attack_moving = true, then immediately called move_to() which set _attack_moving = false and _move_commanded = true. Net result: Vikings flew past every enemy without engaging, behaving identically to a regular move command.</li><li><strong>Repath counter never reset</strong> — _repath_attempts accumulated across chase cycles and SCV harvest round-trips. After enough navigation hiccups, the counter would permanently exceed the threshold, causing units to give up moving after a single stall frame. This manifested as &quot;SCVs randomly go idle&quot; — the kind of bug that&#39;s nearly impossible to reproduce because it depends on movement history.</li></ul><h3>Air Unit Arrival Trembling</h3><p>Medivacs and Vikings would visibly jitter after arriving at a destination. The root cause was architectural: air units disabled the group arrival system (_group_destination = Vector2(-1, -1)), relying solely on the 0.05-tile steering stop threshold. Ground units use a generous 0.3-tile group arrival threshold on top of steering, which absorbs any per-frame position noise. Air units had to hit the exact 0.05 mark or oscillate.</p><p>The fix: air unit move_to() overrides now set a valid _group_destination and reset stall counters, enabling the same two-tier arrival system that ground units use.</p><p>For Medivacs specifically, there was a second oscillation source: _process_healing() would resume movement every frame when a wounded ally sat at exactly the heal range boundary. Adding 0.5-tile hysteresis — only <em>start</em> chasing at HEAL_RANGE + 0.5, but keep chasing until within HEAL_RANGE — eliminated the boundary flutter.</p><h3>EnemyMarine Class Rewrite</h3><p>EnemyMarine was the largest DRY violation in the codebase — 150 lines of mesh-building code copy-pasted from Marine, differing only in color constants. Meanwhile, EnemyMarauder already correctly extended Marauder with virtual color methods.</p><p>The fix: extract _get_body_color(), _get_shoulder_color(), _get_visor_color(), and _get_visor_emission() as virtual methods in Marine, then rewrite EnemyMarine to extend Marine and override only the colors. The class went from 151 lines to 47.</p><pre>class_name EnemyMarine<br>extends Marine</pre><pre>func _get_body_color() -&gt; Color:<br>    return Color(0.78, 0.15, 0.12)<br>func _get_shoulder_color() -&gt; Color:<br>    return Color(0.85, 0.20, 0.15)<br>func _get_bullet_color() -&gt; Color:<br>    return Color(1.0, 0.35, 0.2)</pre><h3>Convention Compliance Sweep</h3><p>The review caught systematic violations of two CLAUDE.md rules across multiple spawn functions:</p><ul><li><strong>Rule 2 (force_ground first)</strong> — six building spawn functions were missing the terrain-clearing call. They worked because occupy_footprint() clears ground internally, but the rule exists to prevent race conditions during building setup.</li><li><strong>Rule 21 (faction before add_child)</strong> — all three enemy unit classes set faction = 1 inside _ready() instead of before add_child(). The AI supply depot and refinery spawners had the same issue. Any future code reading faction during _init_building() would silently see the wrong value.</li></ul><h3>Other Fixes</h3><h4>KEY_E Double-Binding</h4><p>Selecting a Siege Tank and Barracks together, then pressing E, would toggle siege mode and silently consume the keypress — Medic training never fired. Fixed by only returning after all tanks are toggled.</p><h4>Siege Tank Dead Pre-Check</h4><p>The min-range check before super._process_combat() was always undone when the parent re-acquired the same target. Removed the redundant pre-check, keeping only the post-check.</p><h4>Spawn Function Returns</h4><p>All 7 unit spawn functions now return the created unit. _on_unit_trained_from() used get_children().back() — fragile if a spawn function ever adds a side-effect child node.</p><h4>Fog Visibility Ownership</h4><p>Enemy unit visibility was written twice per frame — once by the unit, once by main.gd. Removed the unit-side write; main.gd is now the sole authority for all entity types.</p><h3>Game Speed Toggle</h3><p>A small but frequently-requested feature: an <strong>[F10] button</strong> in the right sidebar that toggles between <strong>Normal</strong> (1.0×) and <strong>Faster</strong> (1.4×) game speed. SC2 online defaults to Faster, but Normal is useful for learning unit interactions and debugging movement.</p><p>The implementation is trivial — Engine.time_scale is either 1.0 or 1.4 — but getting the speed <em>right</em> required verifying the entire conversion system. SC2 uses a fixed-rate game loop at 16 loops per game-second, with Faster running those loops at 1.4× real time (22.4 loops/sec). Our Engine.time_scale = 1.4 is the exact equivalent: all game logic uses Normal-speed values, and the engine multiplier converts them to Faster automatically.</p><h3>What’s Next</h3><p>The game has crossed another threshold. Units don’t just fight — they <em>breathe</em>, fidget, and react. The audio is spatial. The UI communicates garrison contents, production queues, and building footprints. Static defenses create map control decisions. The movement system is now rock-solid after a 10-bug fix pass. The next phases push into new territory:</p><ul><li><strong>Phase 19:</strong> Ramps, high/low ground &amp; destructible rocks — terrain that affects gameplay</li><li><strong>Phase 23:</strong> Hellion, Reaper &amp; active abilities — expanding the unit roster</li><li><strong>Phase 27:</strong> Ghost, cloaking &amp; detection — stealth mechanics</li><li><strong>Phase 28:</strong> 3D models &amp; visual polish — replacing placeholder boxes with real geometry</li></ul><p>Every mesh is still a colored box. Every texture is procedurally generated. The entire game runs from a single main.gd that builds the scene tree in code. But when a Marine fidgets at their post, a Siege Tank shell arcs across the map, the combat sounds fade as you pan away, and you click a Bunker icon to eject a wounded unit — it&#39;s starting to feel like the real thing.</p><p><em>— Built with Godot 4.6, GDScript, and an unreasonable amount of determination</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5804154af22a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Market as Multi-Agent RL: Why Wall Street Is the Hardest Game]]></title>
            <link>https://augustdeepthink.medium.com/the-market-as-multi-agent-rl-why-wall-street-is-the-hardest-game-569b0672142c?source=rss-310dfdf9c269------2</link>
            <guid isPermaLink="false">https://medium.com/p/569b0672142c</guid>
            <dc:creator><![CDATA[Thinking in AI, Philosophy, Investing, and Mind]]></dc:creator>
            <pubDate>Wed, 18 Mar 2026 23:26:43 GMT</pubDate>
            <atom:updated>2026-03-18T23:26:43.379Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Market as Multi-Agent RL: Why Wall Street Is the Hardest Game (Crafted with AI)</h3><p>The previous post argued markets are neural networks — prices as embeddings, P&amp;L as backprop, crashes as gradient explosion.</p><p>But that’s not quite right. Or not complete.</p><p>Markets aren’t supervised learning. There’s no labeled dataset. No ground truth. No teacher providing correct answers.</p><p>Markets are reinforcement learning. And not single-agent RL. Multi-agent RL with non-stationary dynamics, partial observability, and adversarial opponents who adapt to your policy.</p><p>This is why markets are hard. Not because they’re random. Because they’re the most sophisticated RL environment humans have ever built.</p><h3>The Basic Setup</h3><p>In RL, an agent observes state, takes action, receives reward, updates policy.</p><p><strong>Agent:</strong> Trader, fund, algorithm — any market participant making decisions.</p><p><strong>Environment:</strong> The market itself. Order books, prices, news flow, other participants.</p><p><strong>State:</strong> Everything you can observe. Prices, volume, fundamentals, sentiment, your own portfolio, your own P&amp;L.</p><p><strong>Action:</strong> Buy, sell, hold. What instrument, what size, what timing.</p><p><strong>Reward:</strong> P&amp;L. The market’s unambiguous feedback signal.</p><p><strong>Policy:</strong> Your trading strategy. The mapping from observed state to action.</p><p>Every trader is running policy gradient descent. Take actions, observe rewards, update policy. Repeat until bankruptcy or retirement.</p><h3>The Credit Assignment Problem</h3><p>Here’s the first deep difficulty: what caused your reward?</p><p>You made money this month. Was it your stock picks? Your timing? Your position sizing? Your risk management? Or did the whole market go up and you just happened to be long?</p><p>RL calls this credit assignment — figuring out which actions actually caused the reward. In markets, it’s brutally hard.</p><p>A trader might run a profitable strategy for years without knowing why it works. They have a policy that generates rewards, but the causal structure is opaque. Then the market changes, the strategy fails, and they still don’t understand what happened.</p><p>Most trading blowups are credit assignment failures. Traders who thought they were skilled when they were lucky. Policies that appeared robust but were actually exploiting temporary structure.</p><h3>Exploration vs. Exploitation</h3><p>Every RL agent faces this tradeoff: exploit what you know works, or explore to find something better?</p><p>In markets, this is existential.</p><p><strong>Pure exploitation:</strong> Stick with your proven strategy. It’s worked for years. The expected reward is positive. Why risk capital on untested ideas?</p><p><strong>Pure exploration:</strong> The market changes. What worked yesterday may not work tomorrow. If you don’t explore, you’ll eventually be exploited by those who did.</p><p>The market punishes both extremes. Pure exploiters get killed by regime change. Pure explorers burn capital on experiments that mostly fail.</p><p>Every successful trader has solved this tradeoff — usually through some form of portfolio allocation. Core capital runs proven strategies (exploitation). Smaller allocations test new ideas (exploration). The ratio shifts based on confidence and market conditions.</p><p>This is Thompson Sampling with real money. Epsilon-greedy with your career on the line.</p><h3>Multi-Agent Non-Stationarity</h3><p>Single-agent RL is hard. Multi-agent RL is theoretically nightmarish.</p><p>When other agents are learning simultaneously, the environment becomes non-stationary. Your optimal policy depends on their policies, which are changing, which means your optimal policy is changing, which means…</p><p>Markets are the purest form of this.</p><p>Every profitable strategy creates incentives for others to discover it. Once discovered, it gets arbitraged. The reward signal degrades. The policy that worked stops working — not because you did anything wrong, but because the environment adapted to you.</p><p>This is Red Queen dynamics. You have to run just to stay in place. Your policy must improve continuously merely to maintain performance.</p><p>It also means the efficient market hypothesis is both true and useless. Markets are approximately efficient because RL agents are continuously arbitraging inefficiencies. But “approximately efficient” leaves room for reward — if you can find inefficiencies faster than they’re arbitraged.</p><h3>The Sim-to-Real Gap</h3><p>RL practitioners know this problem intimately: policies trained in simulation often fail in reality.</p><p>In finance, this is the backtest-to-live gap.</p><p><strong>Backtest:</strong> Historical simulation. You test your policy on past data. It looks amazing. 40% annual returns, low drawdowns, beautiful equity curve.</p><p><strong>Live trading:</strong> Everything breaks. Slippage is higher than simulated. Fills are worse. Liquidity evaporates when you need it. Correlations shift. The strategy that backtested beautifully loses money in production.</p><p>Why? Because backtests are off-policy evaluation. You’re estimating the value of a policy using data generated by different policies (the actual historical traders). This creates systematic biases.</p><p>More fundamentally: in backtest, your actions don’t affect the environment. In live trading, they do. Large enough orders move prices. Your own trading is part of the state transition dynamics.</p><p>The sim-to-real gap is why most quantitative strategies fail. Not because the researchers are stupid. Because they’re solving a subtly different problem than they think they’re solving.</p><h3>Partial Observability</h3><p>In textbook RL, the agent observes the true state. In real RL, you observe partial, noisy signals.</p><p>Markets are severely partially observable.</p><p>You see prices. You don’t see order flow until it hits the tape. You don’t see what other agents are planning. You don’t see the true beliefs of counterparties. You don’t see the full information set that’s priced in.</p><p>Every market participant is doing inference under uncertainty. Trying to estimate the hidden state from observable signals. Building models of other agents’ beliefs. Updating as new information arrives.</p><p>This is POMDP — partially observable Markov decision process. The hardest RL setting. You need to maintain beliefs over hidden states and act on those beliefs, knowing they’re probably wrong.</p><p>Technical analysis is feature engineering for partial observability — trying to extract hidden state from price patterns. Fundamental analysis is building a model of the hidden state directly. Both are attempts to solve the partial observability problem.</p><h3>Reward Hacking</h3><p>Every RL agent is susceptible to reward hacking — finding ways to maximize the measured reward that don’t align with the true objective.</p><p>Markets are full of this.</p><p><strong>Sharpe ratio gaming:</strong> Take on hidden tail risk. Strategy looks low-volatility until it blows up catastrophically. High measured Sharpe, terrible true risk-adjusted returns.</p><p><strong>Benchmark hugging:</strong> Mutual funds that closely track their benchmark. They can’t underperform much, so they survive. They also can’t outperform much, but that’s not what they’re optimizing for.</p><p><strong>Window dressing:</strong> Buying winners and selling losers right before reporting dates. Makes the portfolio look good. Doesn’t improve actual returns.</p><p><strong>Short-termism:</strong> Traders optimizing quarterly P&amp;L at the expense of long-term strategy health. They’re maximizing the reward signal they’re evaluated on.</p><p>Goodhart’s Law — when a measure becomes a target, it ceases to be a good measure — is the human-readable version of reward hacking. Markets discovered this long before RL researchers did.</p><h3>Model-Based vs. Model-Free</h3><p>RL has two broad paradigms:</p><p><strong>Model-free:</strong> Learn policies directly from experience. Don’t try to understand the environment’s dynamics. Just learn what works.</p><p><strong>Model-based:</strong> Build an explicit model of how the environment works. Use the model to plan actions.</p><p>Both exist in markets.</p><p><em>Model-free approaches:</em> Pure technical analysis. Momentum strategies. Statistical arbitrage that doesn’t care why the pattern exists, only that it does. “The chart says buy, so I buy.”</p><p><em>Model-based approaches:</em> Fundamental investing. Macro analysis. You build a causal model — this company’s earnings will grow because of these factors, this currency will appreciate because of these dynamics — and trade based on model predictions.</p><p>The tradeoff is familiar to RL researchers. Model-free is more robust to model misspecification but less sample-efficient. Model-based can be more efficient but fails badly when the model is wrong.</p><p>Most sophisticated traders use both. Models for strategic direction. Model-free adaptation for tactical execution.</p><h3>Temporal Difference Learning</h3><p>TD learning updates value estimates incrementally as new information arrives, rather than waiting for episode completion.</p><p>Markets do this continuously.</p><p>A value investor doesn’t wait years to update their thesis. New earnings report: update. Management change: update. Competitive threat: update. Each piece of information shifts the estimated value.</p><p>This is TD(λ) in practice. The present value of a stock is the discounted sum of expected future cash flows. Every new signal updates that expectation, which updates the price, which updates everyone’s estimate of everyone else’s estimate.</p><p>Market prices are TD targets. They represent the current consensus estimate of discounted future value. Trading is betting your TD estimate is better than the market’s.</p><h3>Curriculum Learning</h3><p>Training RL agents on hard problems from scratch often fails. Better to start with easier versions and gradually increase difficulty.</p><p>Traders do this instinctively.</p><p>Start with paper trading (no real stakes). Graduate to small positions. Build to larger size as competence increases. Take on more complex instruments as skills develop.</p><p>Prop trading firms are explicit about this. New traders get limited capital and simple strategies. Survivors get more capital and complexity. The curriculum is built into career progression.</p><p>The market itself provides curriculum learning. Bull markets are “easier” — more strategies work, feedback is more forgiving. Traders who learned in bull markets get their hard curriculum when the bear market arrives.</p><h3>Inverse Reinforcement Learning</h3><p>IRL tries to infer an agent’s reward function from observed behavior. What are they actually optimizing?</p><p>This is half of trading.</p><p>You watch what other agents do — the flow, the positioning, the public statements — and try to infer their objectives. Is this hedge fund building a position or exiting? Is this central bank intervening or testing? Is this insider trading or coincidence?</p><p>If you can infer their reward function, you can predict their future actions. If you can predict their actions, you can position accordingly.</p><p>Every market participant is running IRL on every other participant. Simultaneously, they’re trying to obscure their own reward function so others can’t predict them.</p><p>This is adversarial IRL. You’re inferring objectives from opponents who are actively trying to prevent inference. Good luck with that.</p><h3>The Meta-Game</h3><p>Here’s the deepest level.</p><p>In single-agent RL, you optimize policy against a fixed environment. In multi-agent RL, you optimize policy against other optimizing agents. But there’s a level beyond.</p><p>The best market participants aren’t just optimizing policies. They’re choosing which game to play.</p><p>Which market? Which instrument? Which time horizon? Which strategy class? These meta-choices determine the reward landscape you’re operating in.</p><p>A brilliant RL agent in an adversarial environment with negative expected value will still lose. Game selection — choosing environments where you have edge — dominates policy optimization within a fixed environment.</p><p>Warren Buffett isn’t the best at multi-agent adversarial RL. He’s good at finding games where the competition is weak and the expected value is positive. Then he runs simple policies in favorable environments.</p><p>This is why the best traders often look less sophisticated than quants. They’re optimizing the meta-game: which environments to enter, which to avoid, when the game itself has changed.</p><h3>Why Markets Are the Ultimate RL Benchmark</h3><p>If you wanted to design the hardest possible RL environment, you’d want:</p><ul><li>Partial observability ✓</li><li>Non-stationary dynamics ✓</li><li>Multi-agent competition ✓</li><li>Adversarial opponents ✓</li><li>High-dimensional state space ✓</li><li>Credit assignment over long horizons ✓</li><li>Severe sim-to-real gap ✓</li><li>Agents that adapt to your policy ✓</li><li>Survival constraints (you can go bankrupt) ✓</li><li>No ground truth or teacher signal ✓</li></ul><p>Markets have all of this.</p><p>Every improvement in RL — better exploration, better credit assignment, better transfer, better multi-agent methods — could potentially improve trading. And every trading insight — risk management, regime detection, adversarial thinking — could potentially improve RL.</p><p>The fields are isomorphic. They’re studying the same problem in different languages.</p><h3>The Humbling Implication</h3><p>Here’s what this framework makes clear: beating markets is an AI-complete problem.</p><p>Not in the sense that it requires AGI. In the sense that it requires solving fundamental problems in learning, adaptation, multi-agent interaction, and partial observability — problems we’re nowhere close to solving in general.</p><p>The traders who consistently beat markets aren’t doing something simple. They’ve solved some subset of these problems, at least partially, at least temporarily, in some specific domain.</p><p>When your RL agent can consistently beat markets, you’ve made progress on some of the hardest problems in the field.</p><p>Until then, markets remain the benchmark that benchmarks the benchmarkers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=569b0672142c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building StarCraftZero from Scratch — Part 10: Unit movement problem; and overall game progress (v0.]]></title>
            <link>https://augustdeepthink.medium.com/building-starcraftzero-from-scratch-part-10-unit-movement-problem-and-overall-game-progress-v0-f878abb4c36c?source=rss-310dfdf9c269------2</link>
            <guid isPermaLink="false">https://medium.com/p/f878abb4c36c</guid>
            <dc:creator><![CDATA[Thinking in AI, Philosophy, Investing, and Mind]]></dc:creator>
            <pubDate>Tue, 17 Mar 2026 13:34:46 GMT</pubDate>
            <atom:updated>2026-03-17T13:34:46.513Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building StarCraftZero from Scratch — Part 10: Unit movement problem; and overall game progress (v0.4.4)</h3><p><em>March 15, 2026</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FAPGhLFW3QK8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DAPGhLFW3QK8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FAPGhLFW3QK8%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/463fc26bdca5b3d2b15108cc5f4ff39e/href">https://medium.com/media/463fc26bdca5b3d2b15108cc5f4ff39e/href</a></iframe><p>This update tackles one of the most frustrating problems in RTS development: <strong>how units move as a group</strong>. What sounds trivial — “select units, right-click somewhere” — turns out to be a deep design problem that affects how the entire game feels. I also fixed a fundamental issue with air and ground unit collision that had been lurking since Medivacs and Vikings were added.</p><h3>The Problem: Why Group Movement Was Broken</h3><p>Until now, when you selected a group of units and right-clicked a destination, <strong>every single unit received the exact same destination point</strong> — the pixel where your mouse cursor clicked. This is actually how some RTS engines work internally, relying on collision separation to sort things out on arrival.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*s1TjOmLIPkEN8BYH8M8d-Q.gif" /></figure><p>In practice, it was a disaster. Here’s what would happen:</p><ul><li><strong>Convergent paths</strong> — all units funneled toward a single point, their trajectories crossing and colliding en route</li><li><strong>Arrival pile-up</strong> — faster units (like stimmed Marines) would reach the destination first, then slower units would arrive and bump into them endlessly</li><li><strong>Spinning</strong> — units caught in collision loops would spin in place, unable to reach the exact click point because it was already occupied</li></ul><p>The result felt nothing like StarCraft II, where groups glide smoothly across the map and arrive in a natural cluster, ready for combat.</p><h3>The Solution: Formation-Preserving Offset Destinations</h3><p>After researching how SC2 handles group movement — including James Anhalt’s GDC talk on SC2’s navigation system, reverse-engineering community analysis, and general RTS formation literature — I settled on a solution that prioritizes <em>feel</em> over simulation accuracy.</p><h3>The Core Idea</h3><p>Instead of sending all units to the same point, each unit gets its own destination that preserves its <strong>relative position within the group</strong>. If a Marine is to the left of the group’s center, it moves to a point that’s to the left of the click destination. If a Siege Tank is behind the group, it arrives behind the click point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-5HohAnisiYjX4gfO5wnCQ.jpeg" /></figure><p>The algorithm:</p><ol><li>Compute the <strong>group center</strong> — the average position of all selected units</li><li>For each unit, calculate its <strong>offset</strong> from the group center</li><li>Each unit’s destination becomes <strong>click point + its offset</strong></li><li>The result: roughly parallel movement paths that rarely intersect</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NHJsaJtFuYWaUOW-Uvb1zA.png" /></figure><h3>The Scaling Problem</h3><p>Naive formation preservation has a major flaw: if your units are spread across half the map when you select them, they’d arrive equally spread out. That’s terrible for combat — you want your army to arrive as a <strong>tight, combat-ready cluster</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QRnEGXHLIerxpHMKpw8XLQ.jpeg" /></figure><p><strong>The key insight:</strong> The arrival radius should scale with the number of units, not with how spread out they were originally. Two units should arrive nearly touching. Twenty units need more space, but should still be clustered.</p><p>The formula is elegant: the maximum arrival radius is <strong>sqrt(N) × 0.7 tiles</strong>, where N is the number of units. If the group’s current spread exceeds this radius, all offsets are scaled down proportionally. The shape is preserved, but the scale shrinks.</p><ul><li><strong>2 units:</strong> max radius ~1.0 tile — they arrive practically touching</li><li><strong>5 units:</strong> max radius ~1.6 tiles — tight cluster</li><li><strong>10 units:</strong> max radius ~2.2 tiles — comfortable spacing</li><li><strong>20 units:</strong> max radius ~3.1 tiles — natural army formation</li></ul><p>If the group is already tighter than the max radius, the offsets are used as-is. No unnecessary spreading.</p><h3>Before &amp; After</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*29I2tbZKmDRgZRALSjnldA.gif" /><figcaption>(Before 1)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*mnM5n2bsuXyAZ44EmsBdjA.gif" /><figcaption>(Before 2)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*kQMbZWGwixvI78qEqUYnrg.gif" /><figcaption>(After)</figcaption></figure><p><em>[Video: Group movement comparison — before (convergent spinning) vs after (parallel formation movement)]</em></p><h3>Air &amp; Ground: Separate Worlds</h3><p>While testing the new group movement with mixed armies — Marines and Medivacs moving together — I noticed something wrong: <strong>Medivacs were bumping into Marines’ heads</strong>. Air units were colliding with ground units as if they existed on the same plane.</p><p>In StarCraft II, air and ground units occupy completely separate collision layers. A Medivac flies over a group of Marines without disturbing them. A Viking in fighter mode glides over Siege Tanks without collision. This is fundamental to how mixed armies work.</p><h3>What Was Wrong</h3><p>The collision system had no concept of layers. Every unit — whether flying or walking — was treated identically by the steering, separation, and arrival systems. This caused:</p><ul><li>Medivacs pushing Marines around when flying overhead</li><li>Ground units’ pathfinding treating air unit positions as obstacles</li><li>Transitive arrival detection incorrectly triggering between layers — a landed Marine could cause an overhead Medivac to stop early</li><li>Vikings in fighter mode using ground-based A* pathfinding to chase targets, routing around buildings instead of flying straight</li></ul><h3>The Fix</h3><p>Air and ground units now exist on <strong>completely separate collision layers</strong>. The separation was applied across every system that handles unit-to-unit interaction:</p><ul><li><strong>Steering separation</strong> — units only dodge units on their own layer</li><li><strong>Idle spread</strong> — arrived units only push apart units on their own layer</li><li><strong>Transitive arrival</strong> — a ground unit’s arrival doesn’t affect an air unit overhead</li><li><strong>Pathfinding avoidance</strong> — ground units don’t treat air positions as blocked tiles</li><li><strong>Walkability</strong> — air units always consider all terrain walkable</li><li><strong>Viking chase</strong> — fighter-mode Vikings now fly directly to targets instead of pathfinding around buildings</li></ul><p>The beauty of the implementation is that future air units only need to set a single flag — the entire collision layer system is handled by the base class.</p><h3>Combat Gameplay Walkthrough</h3><p>With formation movement and proper air/ground separation, mixed army combat finally feels right. Here’s a full gameplay session showing everything in action:</p><p><em>[Video: Full combat gameplay walkthrough — building a base, training an army, and engaging the AI opponent]</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f878abb4c36c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building OpenStarCraft from Scratch — Part 8: Armor Types & Bonus Damage]]></title>
            <link>https://augustdeepthink.medium.com/building-openstarcraft-from-scratch-part-8-armor-types-bonus-damage-9060c3a76b5d?source=rss-310dfdf9c269------2</link>
            <guid isPermaLink="false">https://medium.com/p/9060c3a76b5d</guid>
            <dc:creator><![CDATA[Thinking in AI, Philosophy, Investing, and Mind]]></dc:creator>
            <pubDate>Mon, 16 Mar 2026 01:54:35 GMT</pubDate>
            <atom:updated>2026-03-16T01:54:35.677Z</atom:updated>
            <content:encoded><![CDATA[<p><em>March 14, 2026</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*uKURwWVdWdHWK__dgesz9Q.gif" /></figure><p>In <a href="https://medium.com/p/32ec162a7fda?postPublishedType=initial">Part 7</a>, we fixed group movement with stall-gated transitive arrival, refactored the movement code, and expanded the map to 48×48. The game played well, but combat was flat — every unit dealt the same damage to every target. In real StarCraft, unit composition matters because of <em>armor types</em> and <em>bonus damage</em>.</p><p>This update implements SC2’s armor type system: every unit and building gets tagged with armor types, and certain weapons deal bonus damage against specific tags. It’s a small amount of code with a big gameplay impact.</p><h3>How SC2’s Armor System Works</h3><p>In StarCraft 2, every unit has one or more <strong>armor tags</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9z5GhLwiSv06ROIWVnH7zA.png" /></figure><p>Units can have multiple tags — a Marine is both <em>Light</em> and <em>Biological</em>, while an SCV is <em>Light</em>, <em>Biological</em>, <em>and Mechanical</em>. Some weapons deal extra damage to units with a specific tag. The Siege Tank’s cannon does +10 bonus damage to anything tagged <em>Armored</em>, making it devastating against other tanks but merely adequate against Marines.</p><p>This system drives the entire rock-paper-scissors of SC2 unit composition. Without it, there’s no reason to build anything besides the cheapest unit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nghA07DuW9G0rNLYkUe4fg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*T1UaaXiYX2B6DRlxjF_uxA.gif" /></figure><p><em>The info panel now shows armor tags and bonus damage — Siege Tank deals +10 vs Armored in mobile mode.</em></p><h3>Implementation</h3><p>The armor tag infrastructure was already in place from earlier phases — the ArmorTag enum and armor_tags array existed, and units were already tagged. What this phase adds is <strong>SC2-accurate bonus damage values</strong>, <strong>upgrade scaling for bonus damage</strong>, and <strong>armor tags on buildings</strong>.</p><h3>Tags on Every Entity</h3><p>Every unit already had its armor tags set correctly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FpAs1s2Wv4YrO1macaxj5g.png" /></figure><p>The missing piece was <strong>buildings</strong>. In SC2, all Terran buildings are <em>Armored</em> and <em>Mechanical</em>. Previously, the building attack code hardcoded an Armored check:</p><pre># Old — hardcoded, no tag check<br>if bonus_damage &gt; 0 and bonus_target_tag == ArmorTag.ARMORED:<br>    dmg += bonus_damage</pre><p>Now buildings carry proper tags, and the damage code uses the same tag-matching logic as unit combat:</p><pre># New — tag-based, same as unit attacks<br>if bonus_damage &gt; 0 and bonus_target_tag &gt;= 0:<br>    var bld_tags = building.get(&quot;armor_tags&quot;)<br>    if bld_tags != null and bld_tags.has(bonus_target_tag):<br>        dmg += bonus_damage + _get_bonus_weapon_bonus()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*P5XcDm0ynmyszecbBATgdw.gif" /></figure><p><em>Buildings now display their armor tags — all Terran structures are [Armored, Mechanical].</em></p><h3>Bonus Damage Upgrade Scaling</h3><p>In SC2, bonus damage scales with weapon upgrades — usually +1 per upgrade level. For example, a Siege Tank with Vehicle Weapons Level 2 deals 15+4 base damage <em>and</em> 10+2 bonus damage vs Armored.</p><p>We added a new virtual method _get_bonus_weapon_bonus() that returns 0 by default. The Siege Tank overrides it:</p><pre>func _get_bonus_weapon_bonus() -&gt; int:<br>    return UnitBase.vehicle_weapons_level   # +1 per level</pre><p>This keeps the upgrade system extensible — when we add the Marauder later (which also has scaling bonus damage vs Armored), it just overrides the same method.</p><h3>Siege Tank SC2 Accuracy Pass</h3><p>While implementing bonus damage, we cross-referenced every Siege Tank stat against Liquipedia and found several values that had drifted from SC2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*smvHPSvzHDi2WQ9-1Ds1Kg.png" /></figure><p>The siege mode bonus damage fix is the most impactful gameplay change — a sieged tank now deals 40+30 = <strong>70 damage</strong> to armored targets (up from 35+15 = 50). That’s a 40% damage increase against other tanks and buildings. Siege mode now feels properly terrifying.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*uKURwWVdWdHWK__dgesz9Q.gif" /></figure><p><em>Sieged tanks now deal 70 damage to armored targets — a significant buff that matches SC2’s devastating siege mode.</em></p><h3>Info Panel Improvements</h3><p>The selection info panel now shows richer combat information:</p><ul><li><strong>Bonus damage target</strong> — shows the actual tag name (e.g., “+10 vs Armored”) instead of a hardcoded string. This future-proofs for when we add units with bonus damage vs Light.</li><li><strong>Upgrade-scaled bonus</strong> — the displayed bonus damage includes weapon upgrade bonuses, so what you see matches what you deal.</li><li><strong>Building armor stats</strong> — buildings now show their actual armor value and tags instead of a hardcoded “Armor: 1”.</li></ul><p><em>Marine info shows [Light, Biological] with no bonus damage. Siege Tank shows [Armored, Mechanical] with +10 vs Armored.</em></p><h3>What Changed (The Numbers)</h3><p><strong>5 files changed.</strong> A focused, surgical update:</p><ul><li>unit_base.gd — added _get_bonus_weapon_bonus() virtual method, bonus damage now scales with upgrades in both unit and building attacks</li><li>siege_tank.gd — HP 160→175, siege damage 35→40, siege bonus +15→+30, override _get_bonus_weapon_bonus()</li><li>building_base.gd — added armor_tags = [ARMORED, MECHANICAL] to all buildings</li><li>main.gd — info panel shows dynamic bonus target name, upgrade-scaled bonus, building armor tags; refactored _armor_tags_string()</li><li>CLAUDE.md — Phase 15 marked complete</li></ul><h3>What’s Next</h3><p>With armor types and bonus damage in place, unit composition finally matters. Siege Tanks are devastating against armored targets but vulnerable to light swarms. This sets up perfectly for the next phases:</p><ul><li><strong>Phase 16:</strong> Splash Damage &amp; Marauder — area damage for siege mode, plus the Marauder with its +10 vs Armored and Concussive Shells</li><li><strong>Phase 17:</strong> Sound Effects (Second Pass) — siege transformation sounds, building construction, death screams</li><li><strong>Phase 18:</strong> Starport &amp; Air Units</li></ul><p>Five files, one new method, and suddenly the game has a reason to build mixed armies. That’s the beauty of a well-placed damage modifier.</p><p><em>— Built with Godot 4.6, GDScript, Claude Code, and zero art assets.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9060c3a76b5d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building StarCraftZero from Scratch — Part 9: Marauder, Splash Damage, Air Units, Textures &…]]></title>
            <link>https://augustdeepthink.medium.com/building-starcraftzero-from-scratch-part-10-splash-damage-air-units-textures-day-night-971818b7e8da?source=rss-310dfdf9c269------2</link>
            <guid isPermaLink="false">https://medium.com/p/971818b7e8da</guid>
            <dc:creator><![CDATA[Thinking in AI, Philosophy, Investing, and Mind]]></dc:creator>
            <pubDate>Mon, 16 Mar 2026 01:54:02 GMT</pubDate>
            <atom:updated>2026-03-16T01:57:44.370Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building StarCraftZero from Scratch — Part 9: Marauder, Splash Damage, Air Units, Textures &amp; Day/Night</h3><p><em>March 15, 2026</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wAW2K5nLVfkGZgPQeXArAA.png" /></figure><p>In <a href="https://medium.com/p/9060c3a76b5d?postPublishedType=initial">Part 8</a>, we added the Marauder, unit facing, minimap commands, and fixed the game speed. The game was playing more and more like real StarCraft — but it still <em>looked</em> like a box simulator. Every unit was a flat-shaded colored shape. Buildings were featureless slabs. And the lighting never changed.</p><p>This update spans two phases of the roadmap and is the biggest visual overhaul yet. We added splash damage to the Siege Tank, brought the Terran air force online with the Starport, wrapped every unit and building in procedural textures with auto-generated normal maps, and topped it off with a full day/night cycle featuring a NYC-accurate sun model. The boxes are still boxes — but now they look like armored, riveted, battle-worn boxes that cast dramatic shadows at sunset.</p><h3>Splash Damage &amp; the Marauder in Combat</h3><p>Part 9 introduced the Marauder, but its arrival coincided with the bigger splash damage system that transformed the Siege Tank from a single-target sniper into the area devastation weapon it’s supposed to be.</p><h3>The Marauder</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z22mCdWUkBD-53t_2qFAmQ.png" /></figure><p>The Marauder is SC2’s anti-armor infantry — a hulking suit with twin grenade launchers. With the armor type system from Part 8 already in place, adding bonus_damage = 10 against ArmorTag.ARMORED was trivial. The interesting part was the visual design.</p><p>Each arm is a Node3D pivot at shoulder height with a CylinderMesh barrel as a child. The arms <strong>independently track targets</strong> using local-space rotation — the same math as the Siege Tank&#39;s turret, but with two pivots:</p><pre>func _aim_pivot_at(pivot: Node3D, target: Vector3, delta: float) -&gt; void:<br>    var to_target: Vector3 = target - pivot.global_position<br>    var local_dir: Vector3 = global_transform.basis.inverse() * to_target<br>    local_dir.y = 0.0<br>    var desired_yaw: float = atan2(-local_dir.x, -local_dir.z)<br>    var yaw_diff: float = wrapf(desired_yaw - pivot.rotation.y, -PI, PI)<br>    pivot.rotation.y += clampf(yaw_diff, -ARM_TURN_SPEED * delta, ARM_TURN_SPEED * delta)</pre><p>When a target is in range, both arms snap to track it. When idle, the arms lower to a 30° resting angle. Attacks alternate between left and right arms — giving that distinctive SC2 Marauder firing rhythm. (Fun fact: the real SC2 Marauder fires <strong>one grenade per attack</strong> after a balance patch. The dual arms are cosmetic — it alternates which arm the single projectile fires from.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EX9tN-x4DdQ2u74h_a54Tg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*JPFgUEB8BDxqRjsi6582Lg.gif" /></figure><p>The EnemyMarauder extends Marauder directly, overriding only faction, colors, and upgrade bonuses — 52 lines for the entire enemy variant. A code review caught a subtle bug: the original enemy Marauder inherited the player&#39;s weapon upgrade bonus, so every time the <em>player</em> researched weapons, enemy Marauders got stronger too.</p><h3>Siege Tank Splash Damage</h3><p>The Siege Tank’s siege mode now deals area damage with SC2-accurate splash radii. Each bullet carries splash parameters, and on impact it checks for nearby units within three damage rings:</p><ul><li><strong>Inner ring</strong> (0.47 tiles): 100% damage</li><li><strong>Middle ring</strong> (0.78 tiles): 50% damage</li><li><strong>Outer ring</strong> (1.25 tiles): 25% damage</li></ul><p>Splash applies to <em>all</em> units in range — including friendly fire, matching SC2 behavior. A cluster of Marines under a sieged tank’s fire melts fast. This single change elevated siege tanks from “a unit that does 40 damage” to “a position that controls an entire area.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*ylIsuDngwrcZnbkW70GQiw.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*mnM5n2bsuXyAZ44EmsBdjA.gif" /></figure><p><em>Marauders engage armored targets up close while a sieged tank’s splash damage devastates grouped units behind them.</em></p><h3>Phase 18: Starport &amp; Air Units</h3><p>The Terran air force arrives. The Starport is the third production building, training two air units that add an entirely new dimension to combat — units that ignore terrain, pathfinding, and collision entirely.</p><h3>Starport</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Acgmz8g9Bv0Yci6KFnuvXQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*29I2tbZKmDRgZRALSjnldA.gif" /></figure><p>The Starport follows the same ProductionBuilding base class as Barracks and Factory — shared production queue with up to 5 slots, rally point with animated flag and pulsing beacon, full command card integration with keyboard hotkeys. Visually it&#39;s a steel-gray box with two cyan landing-bay lights (emission-glowing spheres) and a tall antenna mast.</p><h3>Medivac — The Flying Healer</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SS4CPxOxfPt5WPBlzziGEA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q7w2Nu--KU1K46hysBS78Q.png" /></figure><p>The Medivac is SC2’s replacement for the ground Medic. It hovers at Y=2.0, auto-heals the nearest damaged friendly unit within range, and stretches a green-glowing heal beam cylinder between itself and its target. The mesh has a gray elongated hull, blue cockpit sphere, red cross on top, and two cylindrical thrusters underneath.</p><p>Air movement was the interesting technical challenge. Ground units use AStarGrid2D for pathfinding and Reynolds steering for collision separation. Air units need none of that — they fly in perfectly straight lines:</p><pre>func _process_air_movement(delta: float) -&gt; void:<br>    if not _moving:<br>        return<br>    var dir: Vector2 = _move_dest - world_pos<br>    if dir.length() &lt; 0.1:<br>        _moving = false<br>        world_pos = _move_dest<br>        return<br>    world_pos += dir.normalized() * move_speed * delta<br>    position = iso_map.tile_to_3d(world_pos)<br>    position.y = FLY_HEIGHT</pre><p>No path array, no steering neighbors, no collision radius. Just point and go. Air units fly over buildings, cliffs, rocks, and other units — exactly how SC2 works. The simplicity was refreshing after months of debugging ground movement edge cases.</p><h3>Viking — The Shape-Shifter</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xeCf0A3oywLWLXvJ3B88-g.png" /></figure><p>The Viking is SC2’s signature dual-mode unit. In Fighter mode it’s an air-to-air jet at Y=2.0 with long range. In Assault mode it lands and becomes a ground mech that uses A* pathfinding and collision steering like any other ground unit.</p><p>The mode switch is where things get interesting — both visually and mechanically. The wings rotate 70° (spread in fighter mode, fold down in assault mode), the body material darkens, and the unit transitions between the two completely different movement systems:</p><pre>func toggle_mode() -&gt; void:<br>    if _transitioning:<br>        return<br>    _is_fighter = not _is_fighter<br>    _transitioning = true<br>    _trans_timer = MODE_SWITCH_TIME   # 2 seconds</pre><pre>    if _is_fighter:<br>        can_attack_air = true<br>        _apply_fighter_stats()<br>    else:<br>        can_attack_air = false<br>        _apply_assault_stats()</pre><p>During the 2-second transition, the Viking can’t attack or accept commands — matching SC2’s vulnerability window that punishes poorly-timed mode switches. The wings smoothly animate between positions using lerp on the rotation angle every frame.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*s1TjOmLIPkEN8BYH8M8d-Q.gif" /></figure><p><em>A Medivac heals bio infantry below while Vikings patrol in fighter mode. Air units hover at Y=2.0, casting shadows on the ground below.</em></p><p>Still has bugs! A group of units could cluster together and some of them just spins forever. I have to fix later.</p><h3>Procedural Textures: From Bath Toys to Armor</h3><p>This was the session’s biggest change. Every unit and building went from flat StandardMaterial3D with a single color to <strong>procedural textures with auto-generated normal maps</strong>. The difference is dramatic: the same box geometry suddenly reads as riveted metal plating instead of painted plastic.</p><h3>The Architecture</h3><p>The ProceduralTextures class (378 lines) generates 128×128 grayscale heightmaps entirely in GDScript at runtime. The key insight: textures are <strong>grayscale patterns that describe surface height</strong>, not color. Bright pixels = raised surfaces (rivet heads, plate faces). Dark pixels = recessed features (panel seams, scratches). The actual color comes from the material&#39;s albedo_color tint.</p><p>This means one grayscale texture works for any color — the same “power armor” pattern renders as blue for player Marines and red for enemy Marines without regenerating anything.</p><p>Nine distinct texture types cover all units and buildings:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tOiUi_ZTrhFk-fRbrOQ9lw.png" /></figure><p>Every unit texture also gets a shared _apply_armor_finish() pass — horizontal reinforcement bands every 64 pixels and smooth weathering noise — giving all units a consistent &quot;military hardware&quot; base feel while their unique elements differentiate them.</p><h3>Normal Maps: The Magic Trick</h3><p>Albedo textures alone still look flat — they’re just tinted gray patterns. The real magic is auto-generating <strong>tangent-space normal maps</strong> from the same heightmap data. For each pixel, we sample its four neighbors, compute the surface gradient, and encode the resulting normal vector into RGB:</p><pre>static func _heightmap_to_normal(heightmap: Image) -&gt; Image:<br>    for x in w:<br>        for y in h:<br>            var left:  float = heightmap.get_pixel((x - 1 + w) % w, y).r<br>            var right: float = heightmap.get_pixel((x + 1) % w, y).r<br>            var up:    float = heightmap.get_pixel(x, (y - 1 + h) % h).r<br>            var down:  float = heightmap.get_pixel(x, (y + 1) % h).r</pre><pre>            var dx: float = (left - right) * strength<br>            var dy: float = (up - down) * strength<br>            var normal := Vector3(dx, dy, 1.0).normalized()</pre><pre>            # Encode [-1,1] → [0,1] for RGB storage<br>            normal_img.set_pixel(x, y, Color(<br>                normal.x * 0.5 + 0.5,<br>                normal.y * 0.5 + 0.5,<br>                normal.z * 0.5 + 0.5, 1.0))</pre><p>With normal_scale = 2.0, panel seams cast tiny per-pixel shadows, rivet heads catch specular highlights, and reinforcement bands appear as raised ridges across every surface. The grayscale heightmap serves <strong>double duty</strong>: it&#39;s both the albedo variation (panel lines are darker) <em>and</em> the source for the normal map (panel lines are recessed). One image, two visual effects, zero art files.</p><h3>The PBR Metallic Trap</h3><p>First attempt: crank up metallic to 0.5 to make things look metallic. Result: <em>transparent units</em>.</p><p>In PBR, metallic surfaces get their color from <strong>reflections</strong>, not from albedo. Our dark RTS scene has nothing bright to reflect. High metallic + dark environment = see-through units. The fix was counterintuitive:</p><ol><li><strong>Drop metallic to 0.05–0.10</strong> — the mechanical look comes from normal maps, not reflections. Real military hardware is matte paint over metal anyway.</li><li><strong>Add a procedural sky</strong> — a dark blue-gray ProceduralSkyMaterial gives PBR surfaces minimal reflection data without changing the scene&#39;s visual feel.</li></ol><h3>Texture Caching</h3><p>Textures are cached by <strong>pattern name only</strong>, not by color. A blue Marine and a red enemy Marine share the same cached &quot;power_armor&quot; heightmap and normal map. Each make_power_armor(color) call returns a <strong>new material instance</strong> (with its own albedo color, roughness, metallic) but references the shared cached textures. First spawn of each type pays ~16ms for generation; every subsequent spawn is instant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wAW2K5nLVfkGZgPQeXArAA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uAPc1YEO3hPI0RP7XjMjzA.png" /></figure><p><em>The geometry is identical — only the materials changed. Normal maps make panel seams cast shadows and rivets catch highlights, transforming flat boxes into armored plating.</em></p><h3>Day/Night Cycle</h3><p>Normal maps made lighting <em>matter</em>. A flat-colored box looks the same at any sun angle. A normal-mapped surface transforms dramatically — rivets that were invisible at noon cast long shadows at sunset, panel seams that looked uniform become deep grooves in golden-hour light. The Marauder’s heavy armor plates look completely different at dawn versus midnight.</p><p>This made a day/night cycle irresistible. Press <strong>F8</strong> to toggle it on.</p><h3>NYC Solar Model</h3><p>The sun follows a real-world arc for New York City latitude (40.7°N, spring equinox):</p><ul><li><strong>6:30 AM</strong> — sunrise on the eastern horizon (azimuth 100°), long dramatic shadows</li><li><strong>12:45 PM</strong> — solar noon, sun peaks at 60° elevation crossing south</li><li><strong>7:30 PM</strong> — sunset in the west (azimuth 260°), golden hour light</li><li><strong>Night</strong> — moon traverses west→east across the northern sky</li></ul><p>The 60° peak elevation is deliberate — NYC is too far north for the sun to go directly overhead, so units always cast visible shadows even at solar noon. At 2 PM the sun is still high with short shadows. By 5 PM, shadows are stretching eastward.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dvOG4y0AKFZYXQPWRRsCkQ.png" /></figure><pre># Sun elevation: sine arc from sunrise to sunset<br>var day_progress: float = (hour - SUNRISE) / (SUNSET - SUNRISE)<br>sun_elevation = sin(day_progress * PI) * 60.0   # peaks at 60°<br>sun_azimuth = lerpf(100.0, 260.0, day_progress)  # east → south → west</pre><h3>Smooth Twilight Transitions</h3><p>The first version used a boolean is_day flag. At 7:30 PM, everything snapped from warm sunset to cold moonlight in a single frame. At 6:30 AM, it snapped back. Both transitions were jarring.</p><p>The fix: a continuous sun_factor (0.0 = full night, 1.0 = full day) with <strong>smoothstep</strong> interpolation over 1.5-hour twilight windows on each side. All colors, light energies, and sky tones lerp between night and day palettes using this single factor — no if/else branches, no hard cutoffs:</p><pre># Dawn: smoothstep over 1.5 hours (5:00 AM → 8:00 AM)<br>var p: float = (hour - SUNRISE) / TWILIGHT<br>sun_factor = p * p * (3.0 - 2.0 * p)</pre><pre># All visuals lerp continuously<br>sky_top = N_SKY_TOP.lerp(D_SKY_TOP, sun_factor)<br>ambient = N_AMBIENT.lerp(D_AMBIENT, sun_factor)<br>light_energy = lerpf(0.6, 1.3, sun_factor)</pre><p>Golden hour emerges naturally when sun_factor is between 0.01 and 0.7. The sun is low, so a warm orange-red tint blends in proportional to how close it is to the horizon. No special-case code — just math.</p><h3>Playable Moonlight</h3><p>At night, the directional light becomes the moon — cool blue-white at energy 0.6, with strong blue ambient fill (0.65). The game is <strong>fully playable</strong>: you can see every unit, building, terrain tile, and fog edge. Everything gets a cool blue tint so it <em>feels</em> like night, but nothing is hidden or unclickable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0hHQfGP6hKI6tBGy3Vp3XQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lGgZyQd8GUrTHOl7FyIGiw.png" /></figure><p>The moon sweeps from west to east across the northern sky over the 11 hours of darkness, so shadows keep moving all night. Without this, shadows froze at sunset and stayed static until dawn — 11 hours of identical lighting that broke the day/night illusion.</p><h3>Speed Control</h3><p>Press <strong>F9</strong> (or click the button next to the day/night toggle) to cycle through 1x, 2x, 4x, 8x sun speed. At 8x, a full day cycle takes about 30 seconds — perfect for watching the golden hour sweep across your base. The button shows a live 12-hour clock: [F8] 2:15 PM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*_ZdVxZdoZMtqDeMM7E496g.gif" /></figure><p><em>The same base at four times of day. Normal-mapped surfaces respond dramatically to changing light angles — rivets catch the sunrise, panel seams deepen at sunset, and everything goes cool blue under moonlight.</em></p><p>The original StarCraft 2 doesn’t have this feature! : ]</p><h3>Shadow Quality</h3><p>Moving sun + normal maps + placeholder geometry = suddenly caring about shadow quality. Godot’s default shadow settings produced jagged, stairstepped edges that visibly crawled as the camera panned. Three settings fixed this:</p><ul><li><strong>4096px shadow atlas</strong> (up from 2048) — 4x more shadow map pixels</li><li><strong>4-split cascade mode</strong> — distributes resolution evenly across viewing distance</li><li><strong>Shadow blur = 2.0</strong> — soft-edge PCF filtering smooths remaining stairstepping</li></ul><pre>_sun_light.directional_shadow_mode = DirectionalLight3D.SHADOW_PARALLEL_4_SPLITS<br>_sun_light.shadow_blur = 2.0<br>RenderingServer.directional_shadow_atlas_set_size(4096, true)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qd7qLIhEnF8-esgJKZRaSQ.png" /></figure><p>The result: clean, soft-edged shadows that sweep across the base as the sun arcs overhead. Buildings cast long morning shadows that shrink toward noon and stretch again at sunset. Individual Marines cast tiny but visible shadows on the terrain below them.</p><h3>Production Panel Countdown</h3><p>A small but satisfying addition: the production queue panel now shows live countdown timers with one decimal place on every active entry — construction, training, and research:</p><ul><li>Supply Depot 18.3s</li><li>Rax: Marine 11.7s</li><li>Spt: Medivac 24.1s</li><li>EBay: Infantry Weapons 82.4s</li></ul><p>No more guessing how long until your next unit pops. The timer ticks down smoothly in real-time, making build order execution feel much tighter.</p><h3>Bug Fixes from Code Review</h3><p>Every commit runs through an automated three-agent code review (bugs, quality, conventions). This round caught several issues:</p><ul><li><strong>Enemy Siege Tank lost its red tint after siege toggle.</strong> The _apply_mobile_mesh() function had hardcoded player-green colors, overwriting the enemy&#39;s red tint on every mode switch. Fixed by adding a _base_color field that persists across transitions.</li><li><strong>Moon azimuth extrapolation.</strong> During dusk twilight, moon_progress exceeded 1.0, causing the moon position to extrapolate to 649°. Clamped with clampf().</li><li><strong>Building selection rings invisible.</strong> Building rings were missing no_depth_test and render_priority, so they were z-occluded by the building&#39;s own mesh. Units had these properties; buildings didn&#39;t.</li><li><strong>Selection rings were diamonds, not circles.</strong> TorusMesh parameters rings and ring_segments were swapped — 4 segments around the circular path = square. Swapped to 32 segments for a smooth circle.</li><li><strong>Missing terrain clearing on spawn.</strong> Three building spawn functions (_spawn_supply_depot, _spawn_engineering_bay, _spawn_armory) didn&#39;t call force_ground() before spawning, violating the project&#39;s &quot;every spawn must clear terrain&quot; rule.</li></ul><h3>The Numbers</h3><p>MetricValueUnit types7 (Marine, Marauder, Medic, Siege Tank, SCV, Medivac, Viking)Buildings8 (CC, Barracks, Factory, Starport, Supply Depot, Eng Bay, Armory, Refinery)Texture types9 procedural patterns, each with auto-generated normal mapsArt assets0Total GDScript~10,000 lines across 30+ scriptsCommit diff+2,208 / -216 lines across 57 files</p><h3>What’s Next</h3><p>The game has reached a visual quality inflection point. Normal-mapped procedural textures and dynamic lighting make the placeholder geometry feel like a deliberate art style rather than a missing art pass. Next up:</p><ul><li><strong>Phase 19:</strong> Hellion, Reaper &amp; Active Abilities</li><li><strong>Phase 20:</strong> Bunker, Sensor Tower &amp; Defenses</li><li><strong>Phase 21:</strong> Ghost, Cloaking &amp; Detection</li></ul><p>The boxes keep getting better. And now they cast shadows while they do it.</p><p><em>Part 10 of the </em><a href="https://medium.com/part-9-marauder-minimap-and-game-feel.html"><em>StarCraftZero devlog</em></a><em> — building an RTS from scratch in Godot 4</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=971818b7e8da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building OpenStarCraft from Scratch — Part 7: Group Movement, Building Hierarchy & Map Overhaul]]></title>
            <link>https://augustdeepthink.medium.com/building-openstarcraft-from-scratch-part-7-group-movement-building-hierarchy-map-overhaul-32ec162a7fda?source=rss-310dfdf9c269------2</link>
            <guid isPermaLink="false">https://medium.com/p/32ec162a7fda</guid>
            <dc:creator><![CDATA[Thinking in AI, Philosophy, Investing, and Mind]]></dc:creator>
            <pubDate>Sat, 14 Mar 2026 22:49:13 GMT</pubDate>
            <atom:updated>2026-03-14T22:49:13.167Z</atom:updated>
            <content:encoded><![CDATA[<p><em>March 14, 2026</em></p><p>In <a href="https://medium.com/p/59807e3c0009?postPublishedType=initial">Part 6</a>, we added Reynolds steering, a full sound system, and built a building class hierarchy that cut nearly 900 lines of duplicated code. The game moved and sounded like StarCraft — but when you selected 12 marines and right-clicked a destination, they all froze the instant the first unit arrived. The group movement system was fundamentally broken.</p><p>This update fixes group movement with <em>stall-gated transitive arrival</em>, refactors the movement code into clean modular methods, auto-computes collision radii from meshes, tunes steering for tighter groups, expands the map to 48×48 with rock chokepoints, and makes the AI actually manage its economy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XIyQNtXaoZelUQ1VXuyZ3w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*8Yktr_HPXANs5ePTkZnbew.gif" /></figure><p><em>The expanded 48×48 map — rock ridge through the center creates natural chokepoints between the two bases.</em></p><h3>SC2-Style Group Arrival</h3><p>The core problem: when you move a group of units to a point, only one unit can actually stand on the click point. The rest need to figure out when they’re “close enough” and stop. Our first attempt used <strong>transitive arrival</strong> — when one unit arrives, any neighbor touching it also marks as arrived, propagating outward like a wave.</p><p>This was elegant in theory and catastrophic in practice. Because all units in a moving group are within collision distance of each other (steering keeps them close but not overlapping), the arrival signal cascaded through the entire group in 3–4 frames. <strong>The whole army froze in place the instant the front unit reached the destination.</strong></p><h3>Stall-Gated Transitive Arrival</h3><p>The fix adds a <strong>stall counter</strong>. Each unit tracks whether it’s making progress toward the group destination. Transitive arrival only triggers when the unit has been stalled for 4+ consecutive frames (~67ms at 60fps):</p><ol><li><strong>Direct arrival</strong>: within 0.3 tiles of destination → stop immediately (unchanged)</li><li><strong>Progress tracking</strong>: compare distance-to-destination vs last frame. If distance decreased by at least 15% of full move speed, reset the stall counter. Otherwise, increment it.</li><li><strong>Gated transitive arrival</strong>: touching an arrived neighbor with the same destination <strong>AND</strong> stall counter ≥ 4 → mark arrived.</li></ol><pre>var cur_dist: float = world_pos.distance_to(_group_destination)</pre><pre># Direct arrival<br>if cur_dist &lt;= 0.3:<br>    _mark_group_arrived()<br>    return</pre><pre># Progress tracking<br>if _prev_dist_to_dest &gt;= 0.0:<br>    var progress: float = _prev_dist_to_dest - cur_dist<br>    if progress &gt;= move_speed * delta * 0.15:<br>        _approach_stall_frames = 0    # still making progress<br>    else:<br>        _approach_stall_frames += 1   # stalled this frame</pre><pre># Transitive arrival: must be stalled AND touching arrived neighbor<br>if _approach_stall_frames &gt;= 4:<br>    for neighbor in nearby_arrived_units_with_same_destination:<br>        if touching(neighbor):<br>            _mark_group_arrived()</pre><p>The result: units arrive in layers from front to back. Each unit keeps pushing toward the destination until it physically can’t make further progress. The back units fill in gaps, push around corners, and only stop when they’re truly out of room. It looks natural — exactly how SC2 handles it.</p><p><strong><em>Still has bugs though! Some of them are spinning!</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*D1Uc6CpZdHTvLsNFsGCb0w.gif" /></figure><p><em>12 marines settling at their destination — front units arrived first, others pushed in and settled behind them.</em></p><h3>Idle Spread</h3><p>Once a unit marks as arrived, it enters <strong>idle spread</strong> mode: a gentle separation force pushes overlapping arrived units apart, capped at 30% of move speed. This gives the final “settled” look where units are evenly distributed without any jittering. It’s much softer than active steering — just enough to prevent stacking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*OQti2GbVCnKwFWEtihTC7Q.gif" /></figure><h3>Movement Code Refactor</h3><p>The old _step() method in unit_base.gd was a 110-line monolith handling waypoint advancement, arrival detection, steering, wall-sliding, and stuck detection all in one function. This update breaks it into focused, single-responsibility methods:</p><p>MethodResponsibility_step()Orchestrator — 3 lines, calls the others in order_advance_waypoints()Skip passed waypoints via dot product check_check_waypoint_arrival()Snap to waypoint on arrival, advance or stop_pop_exact_final()Activate pending sub-tile destination_apply_velocity()Compute steering, delegate to _try_move()_try_move()Direct move → axis slide → compass fallback_track_stuck()Count stuck frames, trigger repath</p><p>Three shared helpers eliminate duplicated state management across the file:</p><ul><li>_reset_group_state() — clears arrival tracking (used in 5 places)</li><li>_halt_path() — stops path following without clearing _move_commanded (used by combat code when a unit stops to fire but shouldn&#39;t lose its &quot;player issued move&quot; flag)</li><li>_stop_moving() — full movement termination including command state (used for genuine arrival and give-up)</li></ul><p>The distinction between _halt_path() and _stop_moving() prevents a subtle bug: if combat stops cleared the &quot;player commanded&quot; flag, idle units would auto-engage enemies during a retreat — the exact opposite of what the player intended.</p><h3>Auto-Computed Collision Radii</h3><p>Previously, every unit had a hardcoded collision_radius = 0.3. This caused Marines (small box mesh) and Siege Tanks (large box mesh) to be treated identically for steering and separation. Siege Tanks would overlap because their visual footprint was larger than their collision sphere.</p><p>The new system auto-derives collision radius from each unit’s mesh geometry:</p><pre>func _auto_collision_radius() -&gt; void:<br>    for child in get_children():<br>        if child is MeshInstance3D and child.mesh is BoxMesh:<br>            var box := child.mesh as BoxMesh<br>            var r: float = Vector2(box.size.x, box.size.z).length() * 0.5<br>            best = maxf(best, r)<br>    # Convert from 3D meters to tile-space, add visual padding<br>    collision_radius = (best / 2.0 + 0.15) if best &gt; 0.0 else 0.35</pre><p>This runs as a deferred call after _build_mesh(), so each subclass gets the right radius without manual tuning. Siege Tanks now maintain proper spacing, and Marines cluster tighter — both matching their visual footprints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*0_tVOYHxC_KURT2Pn6iS_g.gif" /></figure><p><em>Mixed army — Marines cluster tightly while Siege Tanks maintain wider spacing, both auto-computed from their mesh sizes.</em></p><h3>Steering Tuning</h3><p>The Reynolds steering parameters from Part 6 produced smooth movement but overly loose groups. Two key tweaks tightened things up:</p><p>ParameterBeforeAfterWhyarrive_slow_radius1.5 tiles0.8 tilesUnits decelerated too early, creating a long &quot;coasting&quot; phase. Tighter radius means snappier stops.separation_weight2.5×1.5×Separation force was too dominant — units pushed apart before converging on the destination. Lower weight lets arrive force win during movement.</p><p>The combined effect: units travel in tighter formations, decelerate later, and spread less during transit. They still separate cleanly on arrival thanks to idle spread.</p><h3>48×48 Map with Chokepoints</h3><p>The map grew from 32×32 to <strong>48×48 tiles</strong>, giving both bases room to breathe and creating a real battlefield in between. The key addition is a <strong>dense rock ridge</strong> running horizontally through the center of the map:</p><ul><li>3 rows thick, spanning 17 tiles wide</li><li>Two narrow gaps for army movement — natural chokepoints</li><li>Flanking rock clusters on both sides of the ridge for visual variety</li><li>28 scattered rock clusters (up from 18) across the rest of the map</li></ul><p>Both bases were repositioned to sit in opposite corners: the player at tile (36, 36) in the bottom-right, the AI at tile (11, 11) in the top-left. The mineral lines, geysers, and starting armies were all adjusted to match.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*wHjOPKk-4sT_ncj9Lkclww.gif" /></figure><p><em>The full 48×48 layout — player base bottom-right, AI top-left, rock ridge with chokepoint gaps in the center.</em></p><h3>Bigger Starting Armies</h3><p>Games no longer start from scratch. Both sides begin with a full economy and standing army:</p><p>PlayerAISCVs1212Marines1212Medics3 — Siege Tanks22Starting Minerals200200Supply Cap (base)30 (up from 15)</p><p>This matches SC2’s standard starting worker count and lets players jump straight into combat and macro instead of watching one SCV mine for five minutes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E9hVLRZhkjqLk2n5oQ5iHQ.png" /></figure><p><em>Game start — 12 SCVs already mining, a standing army of marines, medics, and siege tanks ready for battle.</em></p><h3>Smarter AI Economy</h3><p>The AI opponent got a major economy fix. Previously, enemy SCVs were spawned but never reliably assigned to mine. Three problems conspired:</p><ul><li><strong>Mineral proximity filter too tight</strong> — used a 10-tile radius, but the expanded map placed minerals further from the AI Command Center. Bumped to 15 tiles.</li><li><strong>No idle recovery</strong> — if an SCV’s pathfinding failed on spawn (crowded area), it went idle permanently. No retry.</li><li><strong>Decision loop bailed early</strong> — the AI would execute one action per cycle (train SCV <em>or</em> queue marines, never both), wasting decision ticks.</li></ul><h3>Three-Layer Fix</h3><ol><li><strong>AI Controller reassignment</strong> — every 2-second decision cycle, the AI scans for idle SCVs and sends them to the nearest mineral patch. This runs before other decisions, so lost workers are recovered quickly.</li><li><strong>EnemySCV self-recovery</strong> — idle enemy SCVs independently retry finding a mineral patch every 3 seconds. This catches SCVs that go idle between AI decision ticks.</li><li><strong>Non-bailing decision loop</strong> — the AI now evaluates all priorities in a single pass: reassign idle workers, train SCVs, build barracks, <em>and</em> queue marines — all in one cycle instead of bailing after the first action.</li></ol><p>Worker targets were also scaled up to match SC2 saturation levels:</p><p>DifficultySCV Target (before)SCV Target (after)Easy312Normal416Hard522</p><p><em>The AI base now runs a real economy — 12+ SCVs saturating the mineral line while the barracks trains marines.</em></p><h3>Building Class Hierarchy (Completed)</h3><p>The building hierarchy from Part 6 was designed but not yet committed. This update finalizes it — all seven building scripts now extend from a proper inheritance tree:</p><p>BuildingBase (Node3D) — HP, armor, construction, selection ring</p><p>ProductionBuilding (BuildingBase) — shared production queue<br> Barracks — trains Marines, Medics<br> Factory — trains Siege Tanks</p><p>ResearchBuilding (BuildingBase) — shared research system<br> EngineeringBay — infantry upgrades<br> Armory — vehicle upgrades</p><p>CommandCenter — unique production, deposits<br> SupplyDepot — +8 supply cap<br> Refinery — gas harvesting</p><p>The biggest payoff is type-check cleanup. Every long OR chain like this:</p><pre>if child is CommandCenter or child is Barracks or child is Factory \<br>    or child is SupplyDepot or child is EngineeringBay or child is Armory \<br>    or child is Refinery:</pre><p>became:</p><pre>if child is BuildingBase:</pre><p>This propagated across hp_bar_overlay.gd, selection_manager.gd, iso_map.gd, and main.gd. Duck-typed property access (building.get(&quot;hp&quot;)) was replaced with direct typed access (building.hp), catching errors at parse time instead of silently returning null at runtime.</p><h3>Viewport-Relative HUD</h3><p>The viewport was bumped from 1280×720 to <strong>1920×1080</strong>. All hardcoded HUD positions were replaced with viewport-relative calculations. Every panel — minimap, top bar, bottom bar, info panel, command card, music controls — now computes its position from get_viewport().get_visible_rect().size instead of magic numbers.</p><p>This means the HUD adapts to any resolution, not just the one we happened to test with. Camera pan scaling was also fixed — previously hardcoded to 720p, now uses actual viewport height.</p><p><em>All HUD elements at 1920×1080 — minimap, command card, info panel, and music controls all viewport-relative.</em></p><h3>Other Fixes</h3><ul><li><strong>Supply Depot selection</strong> — Supply Depots gained a selection ring and are now fully selectable (previously excluded from the selection check)</li><li><strong>Camera boundaries</strong> — pan limits updated for the 48-tile map; camera starts centered on the player base at tile (36, 36)</li><li><strong>Attack wave coordinates</strong> — AI rally and attack target tiles repositioned for the larger map so enemies actually march toward the player</li><li><strong>Production info dictionaries</strong> — renamed from UNIT_INFO to BARRACKS_UNIT_INFO / FACTORY_UNIT_INFO to avoid naming collisions after the hierarchy merge</li></ul><h3>What Changed (The Numbers)</h3><p><strong>30 files changed, 888 insertions, 1,086 deletions.</strong> Key changes:</p><ul><li>unit_base.gd — rewritten: group arrival system, modular movement methods, auto collision radius (+234/-136 lines)</li><li>building_base.gd — +87 lines: new shared base class for all buildings</li><li>production_building.gd — +86 lines: shared production queue system</li><li>research_building.gd — +109 lines: shared research system</li><li>7 building scripts — <strong>-892 lines</strong> of duplicated code removed</li><li>iso_map.gd — 32×32 → 48×48, rock ridge with chokepoints (+45 lines)</li><li>main.gd — 12 SCVs per side, larger armies, viewport-relative HUD (+144 lines)</li><li>ai_controller.gd — idle SCV reassignment, non-bailing decisions (+37 lines)</li><li>enemy_scv.gd — auto-harvest retry on idle (+30 lines)</li><li>hp_bar_overlay.gd, selection_manager.gd — BuildingBase type checks replace OR chains</li><li>reynolds_steering.gd — tighter arrive radius and separation weight</li></ul><h3>What’s Next</h3><p>With group movement working properly, the building hierarchy clean, and the AI running a real economy on a battlefield-sized map, the game is starting to feel like an actual RTS. Next on the roadmap:</p><ul><li><strong>Phase 15:</strong> Armor Types &amp; Bonus Damage — light, armored, biological, mechanical tags with SC2-accurate damage bonuses</li><li><strong>Phase 16:</strong> Splash Damage &amp; Marauder</li><li><strong>Phase 17:</strong> Sound Effects (Second Pass) — building construction sounds, siege transformation, death screams</li><li><strong>Phase 18:</strong> Starport &amp; Air Units</li></ul><p>The colored boxes still aren’t going to win any art awards, but they’re moving, fighting, and settling like real StarCraft units now.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32ec162a7fda" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building OpenStarCraft from Scratch — Part 6: Sound, Steering & Architecture]]></title>
            <link>https://augustdeepthink.medium.com/building-openstarcraft-from-scratch-part-6-sound-steering-architecture-59807e3c0009?source=rss-310dfdf9c269------2</link>
            <guid isPermaLink="false">https://medium.com/p/59807e3c0009</guid>
            <dc:creator><![CDATA[Thinking in AI, Philosophy, Investing, and Mind]]></dc:creator>
            <pubDate>Sat, 14 Mar 2026 22:31:25 GMT</pubDate>
            <atom:updated>2026-03-14T22:31:25.113Z</atom:updated>
            <content:encoded><![CDATA[<p><em>March 13, 2026</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*jnAN8stQmeQTIB4fYmUMbQ.gif" /></figure><p>In <a href="https://augustdeepthink.medium.com/building-openstarcraft-from-scratch-part-5-combat-hud-polish-703af25aa5cb">Part 5</a>, we added combat visuals, an SC2-style HUD, and polished the battlefield readability. The game <em>looked</em> right, but it was silent — and under the hood, the codebase was starting to creak. Seven building scripts duplicated the same 50 lines of boilerplate, units jittered at their destinations, and there wasn’t a single sound effect.</p><p>This update tackles all three fronts: <em>physics-based movement</em>, a <em>full sound system</em>, and a <em>major architectural cleanup</em> that cut nearly 900 lines of duplicated code.</p><h3>Reynolds Steering Behaviors</h3><p>The old movement system had a problem: units would reach their destination and then vibrate in place. The position-based separation pushed units apart every frame, but there was no deceleration — units overshot, got pushed back, overshot again. It was the classic jitter loop.</p><p>The fix was to replace the entire movement model with <strong>Reynolds steering behaviors</strong> — the same approach used in most modern RTS games. Instead of adjusting positions directly, we now compute <em>velocity vectors</em> by combining two forces:</p><ul><li><strong>Arrive</strong> — seek the target at full speed, but decelerate smoothly within a slow radius (1.5 tiles). Snap to the destination within 0.05 tiles.</li><li><strong>Separation</strong> — push away from nearby units proportional to how much their collision radii overlap. Weighted 2.5x relative to arrive.</li></ul><p>The two forces are summed, capped to prevent wild accelerations, and applied as a single velocity update. The result: units flow smoothly around each other, decelerate naturally at their destination, and settle into tight formations without jitter.</p><h3>Strategy Pattern</h3><p>The steering code uses a modular design: SteeringStrategy is an abstract base class with a single method — compute_velocity(). ReynoldsSteering extends it with the arrive + separation implementation. This means we can swap in different steering behaviors (flocking, formation movement, boid-style) without touching any unit code.</p><p><em>Units moving across the map — smooth deceleration, natural separation, no jitter on arrival.</em></p><h3>Sound System</h3><p>StarCraft without sound is like chess without a board — technically playable, but missing the soul. This update adds a full audio system with three layers:</p><h3>Procedural SFX</h3><p>Basic game sounds — move commands, attack orders, UI clicks, weapon impacts — are generated procedurally at runtime. No audio files needed. The SoundManager synthesizes short waveforms (noise bursts, sine blips, filtered clicks) and caches them as AudioStreamWAV resources. This keeps the repo lightweight and gives us instant access to dozens of sound effects.</p><h3>Voice Lines</h3><p>SC2’s personality comes from its unit voices. We’ve added MP3 voice lines organized by unit and action:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sTmOhQNtT8gaq9fRYzL_5w.png" /></figure><p>When a unit has multiple voice lines for an action, one is picked at random — just like SC2. A dedicated voice player prevents voice lines from being cut off by rapid SFX fire.</p><h3>Music</h3><p>The audio/music/ folder holds SC2 soundtrack tracks (OGG and MP3). The music system supports crossfading between tracks, pause/resume with F5, and skip-to-next with F6. Music volume is set lower than SFX so it sits in the background where it belongs.</p><h3>Advisor Alerts</h3><p>The Terran advisor now speaks up during gameplay:</p><ul><li><em>“Not enough minerals”</em> / <em>“Additional supply depots required”</em> / <em>“Require more vespene gas”</em> — when a build/train action fails</li><li><em>“Your base is under attack!”</em> — when any player building takes damage (with a 30-second cooldown to prevent spam)</li><li><em>“Research complete”</em> / <em>“Upgrade complete”</em> — when Engineering Bay or Armory finishes research</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FkyWAQtwEgrk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DkyWAQtwEgrk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FkyWAQtwEgrk%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/08ecb0a9f21e6df1096bac021ccf0098/href">https://medium.com/media/08ecb0a9f21e6df1096bac021ccf0098/href</a></iframe><p><em>Full gameplay at 1920x1080 — unit voices, advisor alerts, music, and smooth steering all working together.</em></p><h3>Building Class Hierarchy</h3><p>This is the unglamorous change that made the biggest difference to the codebase. All seven building scripts — Command Center, Barracks, Factory, Supply Depot, Engineering Bay, Armory, Refinery — were standalone Node3D scripts that copy-pasted the same code:</p><ul><li>HP, armor, take_damage(), repair_hp(), is_full_hp()</li><li>Construction progress, advance_construction(), alpha transparency</li><li>Selection ring creation and selected property setter</li></ul><p>On top of that, Barracks and Factory duplicated an identical ~70-line production queue system, and Engineering Bay and Armory duplicated an identical ~90-line research system.</p><h3>The New Hierarchy</h3><p>BuildingBase (extends Node3D)<br> HP, armor, construction, selection ring, alpha<br> take_damage(), repair_hp(), advance_construction()</p><p>ProductionBuilding (extends BuildingBase)<br> Production queue, train_unit(), _process() timer<br> Barracks — 196 → 40 lines<br> Factory — 203 → 48 lines</p><p>ResearchBuilding (extends BuildingBase)<br> Research state machine, level cost/time, _process() timer<br> EngineeringBay — 236 → 82 lines<br> Armory — 223 → 66 lines</p><p>CommandCenter — 184 → 139 lines (keeps unique production)<br> SupplyDepot — 77 → 30 lines (gained selection ring)<br> Refinery — 153 → 84 lines</p><p><strong>Net result: 892 lines deleted, 135 lines added.</strong> Every building script now contains only what makes it unique — its mesh, its stats, and its specific behavior.</p><h3>isinstance Cleanup</h3><p>With a proper class hierarchy, the codebase had 40+ type-check chains like this scattered across six files:</p><pre>if child is CommandCenter or child is Barracks or child is Factory \<br>    or child is SupplyDepot or child is EngineeringBay or child is Armory \<br>    or child is Refinery:</pre><p>Every single one became:</p><pre>if child is BuildingBase:</pre><p>This isn’t just prettier — it’s correct by construction. When we add new building types in the future, they’ll automatically be included in HP bar rendering, fog-of-war vision, enemy targeting, and selection without touching any of those systems. The old approach required updating every OR chain every time a building was added.</p><p>Duck-typed property access (building.get(&quot;hp&quot;)) was also replaced with direct typed access (building.hp), catching potential errors at parse time instead of silently returning null at runtime.</p><h3>Bigger Map &amp; Stronger Start</h3><p>The map grew from 32×32 to <strong>48×48 tiles</strong>. Both bases were repositioned with more breathing room — the Command Center now sits further from the mineral line, matching SC2’s base layout. The extra space isn’t empty: a <strong>rock ridge</strong> runs through the center of the map with two narrow chokepoint gaps, creating natural choke defense and flanking opportunities.</p><p>Games no longer start from scratch. Both the player and the AI begin with <strong>12 SCVs</strong> (SC2’s standard starting worker count), a full army (12 Marines, 3 Medics, 2 Siege Tanks for the player; 12 Marines and 2 Siege Tanks for the AI), and 200 starting minerals. Supply was bumped from 15 to 30 to accommodate the larger starting force. The goal: jump straight into the action instead of spending the first five minutes watching one SCV mine.</p><h3>1920×1080 Resolution</h3><p>The viewport was bumped from 1280×720 to 1920×1080. All hardcoded HUD positions were replaced with viewport-relative calculations, so the layout adapts to any resolution. The minimap, top bar, bottom bar, info panel, and command card all compute their positions from get_viewport().get_visible_rect().size instead of magic numbers.</p><h3>Smarter AI</h3><p>The AI opponent got a significant intelligence upgrade. The biggest fix: enemy SCVs were being spawned but never assigned to mine minerals. Two problems conspired to cause this:</p><ul><li><strong>Distance filter too tight</strong> — the mineral patch proximity check used a 10-tile radius, but the expanded map placed minerals ~9 tiles from the AI Command Center. Marginal rounding or pathfinding failures caused patches to silently fail the filter. Relaxed to 15 tiles.</li><li><strong>No idle recovery</strong> — if an SCV’s pathfinding failed (crowded spawn area, blocked tiles), it went IDLE and stayed there forever. No retry, no reassignment.</li></ul><p>The fix has three layers:</p><ol><li><strong>AI Controller reassignment</strong> — every 2-second decision cycle, the AI scans for idle SCVs and sends them to the nearest mineral patch.</li><li><strong>EnemySCV self-recovery</strong> — idle enemy SCVs independently retry finding a mineral patch every 3 seconds. This catches SCVs that go idle between AI decision ticks.</li><li><strong>Worker targets updated</strong> — SCV target counts raised from 3–5 to 12–22 depending on difficulty, matching SC2-appropriate saturation levels.</li></ol><p>The AI decision loop was also streamlined — it previously bailed after the first action (train SCV <em>or</em> queue marines, never both). Now it evaluates all priorities in a single pass: reassign idle workers, train SCVs, build barracks, and queue marines all in one cycle.</p><p>Attack wave coordinates were updated for the 48-tile map so the AI actually sends units toward the player’s base instead of empty terrain halfway across the map.</p><h3>Bug Fixes</h3><ul><li><strong>Freed-instance crashes</strong> — units and buildings that were queue_free’d could still be referenced by attack targets, selection lists, and control groups. Added is_instance_valid() guards throughout.</li><li><strong>Selection rectangle color</strong> — the box-select rectangle was nearly invisible. Updated to a brighter cyan with better contrast.</li><li><strong>Group movement</strong> — multiple units given the same move command now all receive the exact click point (SC2 behavior). No pre-computed formation offsets — collision separation handles natural spreading on arrival.</li><li><strong>HUD layout issues</strong> — command card slots, info panel, and music controls repositioned for cleaner layout at higher resolution.</li><li><strong>Supply Depot selection</strong> — Supply Depots were previously not selectable (missing from the selection check). Now they have a selection ring and respond to clicks like every other building.</li><li><strong>Camera boundaries</strong> — camera pan limits updated for the 48-tile map. Previously the camera couldn’t reach the player’s base after the map expansion.</li></ul><h3>What Changed (The Numbers)</h3><p><strong>58 files changed across the steering/sound commit, plus 17 files in the architecture pass.</strong> Key changes:</p><ul><li>sound_manager.gd — +655 lines: procedural SFX generation, voice line pools, music crossfade system</li><li>unit_base.gd — +359 lines rewritten: Reynolds steering integration, velocity-based movement</li><li>reynolds_steering.gd — +80 lines: arrive + separation force computation</li><li>building_base.gd — +87 lines: shared building base class</li><li>production_building.gd — +86 lines: shared production queue</li><li>research_building.gd — +109 lines: shared research system</li><li>7 building scripts — <strong>-892 lines</strong> of duplicated code removed</li><li>iso_map.gd — map 32×32 → 48×48, rock ridge with chokepoints</li><li>ai_controller.gd — idle SCV reassignment, worker target scaling, decision loop fix</li><li>enemy_scv.gd — auto-harvest retry on idle</li><li>36 audio files added (voice lines, advisor alerts, music tracks)</li></ul><h3>What’s Next</h3><p>The game now has sound, smooth movement, a clean architecture, a bigger battlefield, and an AI that actually builds an economy. Next on the roadmap:</p><ul><li><strong>Phase 15:</strong> Armor Types &amp; Bonus Damage — light, armored, biological tags with SC2-accurate damage bonuses</li><li><strong>Phase 16:</strong> Splash Damage &amp; Marauder</li><li><strong>Phase 17:</strong> Sound Effects (Second Pass) — building construction sounds, siege mode transformation, death screams</li><li><strong>Phase 18:</strong> Starport &amp; Air Units</li></ul><p>The colored boxes may not look like much, but close your eyes and it’s starting to <em>sound</em> like StarCraft.</p><p><em>— Built with Godot 4.6, GDScript, Claude Code, and zero art assets.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59807e3c0009" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building OpenStarCraft from Scratch — Part 5: Combat, HUD & Polish]]></title>
            <link>https://augustdeepthink.medium.com/building-openstarcraft-from-scratch-part-5-combat-hud-polish-703af25aa5cb?source=rss-310dfdf9c269------2</link>
            <guid isPermaLink="false">https://medium.com/p/703af25aa5cb</guid>
            <dc:creator><![CDATA[Thinking in AI, Philosophy, Investing, and Mind]]></dc:creator>
            <pubDate>Thu, 12 Mar 2026 21:53:37 GMT</pubDate>
            <atom:updated>2026-03-12T21:54:18.826Z</atom:updated>
            <content:encoded><![CDATA[<p><em>March 12, 2026</em></p><p>In <a href="https://augustdeepthink.medium.com/building-openstarcraft-from-scratch-part-4-going-3d-8d7cb15bc71c">Part 4</a>, we converted the entire game from 2D isometric to 3D. The world had depth, but the combat felt lifeless — bullets were invisible, units didn’t react to hits, and the HUD was still the old debug-style text dumps. This update fixes all of that.</p><p>This is the <em>“make it feel like StarCraft”</em> pass.</p><h3>Damage-on-Impact Projectiles</h3><p>Previously, damage was applied the instant a unit fired — the bullet was purely cosmetic. This was fine when bullets were fast and invisible, but now that siege tank shells travel visibly across the battlefield, seeing an HP bar drop <em>before the shell arrives</em> felt wrong.</p><p>The fix: bullets now carry a damage payload. Bullet.set_damage(dmg, target_unit, target_building) stores the damage, and _apply_damage() fires only when the projectile reaches its destination. HP bars, damage numbers, and death all sync perfectly with the visual impact.</p><p>This matters most for siege tanks. Their orange shells travel at speed 30 (vs infantry’s speed 50), giving you a satisfying beat between the cannon firing and the explosion landing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*dNdyefbT0MagiBFSLZPzeQ.gif" /></figure><p><em>A firefight in progress — colored tracers, muzzle flashes, floating damage numbers, and HP bars responding on impact.</em></p><h3>Per-Unit Bullet Visuals</h3><p>Every unit type now has its own distinct bullet appearance, making it easy to read the battlefield at a glance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YizJrX5nBkywKDbbuYOS8A.png" /></figure><p>Every bullet also has an <strong>outer glow</strong> — a larger, semi-transparent sphere (3x the bullet radius) with emission, making projectiles pop against the dark battlefield. Combined with muzzle flashes on the attacker and hit flashes on the target, combat finally has that SC2 energy.</p><h3>Combat Feedback: Flashes &amp; Damage Numbers</h3><p>Three layers of visual feedback now fire during combat:</p><ul><li><strong>Muzzle flash</strong> — a bright sphere appears at the attacker’s position when they fire, fading quickly</li><li><strong>Hit flash</strong> — a red translucent sphere briefly envelops the target on impact</li><li><strong>Floating damage numbers</strong> — red -X text rises from the target and fades over 0.8 seconds, using Label3D so they exist in world space</li></ul><p>The damage numbers were a late addition but immediately made combat 10x more readable. You can now tell at a glance whether your siege tank is chunking for 40 or your marines are poking for 6.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*iCl_SO1ZvRlDgOpRLICQSw.gif" /></figure><p><em>Selecting the army and sending them into battle — multi-selection info panel, command card with Stim Pack and Siege Mode, tracers flying.</em></p><h3>Siege Tank Turret Rotation</h3><p>The siege tank got a proper turret system. A _turret_pivot Node3D parents both the turret cylinder and barrel, rotating as a group at 5 radians/second toward the current target. The barrel extends along the -Z axis, so the rotation math uses atan2(-to_target.x, -to_target.z) — getting this sign wrong was a fun debugging session where the turret pointed exactly opposite to the enemy.</p><p>The turret tracks attack targets, building targets, and even faces the movement direction when driving. Shells fire from the barrel tip position, not the tank’s center. In siege mode, the body widens, the barrel extends, and shells become larger bright orange explosives.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RR50KQQ0-bVBzWOQuiiJjQ.png" /></figure><p><em>Siege tank selected — info panel shows HP 175/175, Dmg 15, Range 7.0; command card offers Siege Mode and Attack Move.</em></p><h3>Medic Heal Beam</h3><p>Medics now display a glowing green beam connecting them to whichever unit they’re healing. The beam is a thin cylinder mesh with emission, stretched each frame between the medic and the heal target. It pulses in opacity with each heal tick and disappears when healing stops or the target is out of range.</p><p>This small visual addition makes medic behavior instantly readable. Before, you had to watch HP bars to know if healing was happening. Now you can see exactly who’s healing whom.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*eoeHlhXImZDmZTOG6oHCnw.gif" /></figure><p><em>Medic heal beam in action — the green laser connects the medic to its heal target, pulsing with each heal tick.</em></p><h3>SC2-Style Command Card</h3><p>The old production panel was a mess — a fixed layout that only worked for barracks. It’s been replaced with a proper <strong>contextual command card</strong> in the bottom-right corner, just like SC2.</p><p>The command card shows different actions depending on what’s selected:</p><ul><li><strong>SCV:</strong> Build (opens structure menu), Attack Move</li><li><strong>Marine:</strong> Stim Pack, Attack Move</li><li><strong>Siege Tank:</strong> Siege/Unsiege Mode, Attack Move</li><li><strong>Barracks:</strong> Train Marine, Train Medic (with queue count and progress bar)</li><li><strong>Factory:</strong> Train Siege Tank</li><li><strong>Engineering Bay:</strong> Research Infantry Weapons/Armor</li><li><strong>Armory:</strong> Research Vehicle Weapons/Armor</li><li><strong>Build menu:</strong> All 6 structure types with costs</li></ul><p>Each slot shows the hotkey, description, and additional info (cost, effect). Slots highlight on mouse hover and are fully clickable. The keyboard shortcuts still work too — the card just makes them discoverable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*y7pyNF-bT5VDY6xa0M8LxA.gif" /></figure><p><em>Army selected — the command card shows Stim Pack, Siege Mode, and Attack Move. The info panel shows “7 units selected”.</em></p><p>Getting clicks to work required solving a Godot input ordering puzzle: ColorRect controls default to mouse_filter = STOP, consuming mouse events before they reach _unhandled_input. Setting all HUD controls to MOUSE_FILTER_IGNORE let clicks pass through to the game&#39;s input handler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d5RspBkW1TEav-zfPUBm0A.png" /></figure><p><em>Three SCVs selected — the info panel shows unit count, and the command card offers Build and Attack Move.</em></p><h3>Unit Info Panel</h3><p>Clicking on any unit or building now shows a <strong>bottom-center info panel</strong> with:</p><ul><li>Unit/building name</li><li>Colored portrait placeholder (each type gets a distinct color)</li><li>HP / Max HP</li><li>Stats: damage, armor, range, speed (or heal stats for Medics)</li><li>Construction progress for buildings under construction</li></ul><p>Multi-selection shows the count of selected units. The panel hides when nothing is selected. HP bar overlays are suppressed behind both the info panel and command card to keep things clean.</p><h3>Always-On HP Bars with SC2 Colors</h3><p>HP bars are now <strong>always visible</strong> on every unit and building — not just when damaged. They use the SC2 color scheme:</p><ul><li><strong>Green</strong> — healthy (above 66%)</li><li><strong>Yellow</strong> — wounded (33%–66%)</li><li><strong>Red</strong> — critical (below 33%)</li><li><strong>Red (always)</strong> — enemy units and buildings</li></ul><p>Selected units get slightly larger bars. Enemy buildings are hidden when outside visible fog. The HP bar overlay also skips drawing bars that fall behind HUD panels, preventing visual clutter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*BOOKOFetTpNeiymX2wXSKw.gif" /></figure><p><em>Always-on HP bars — every unit and building shows health status at a glance. Green for healthy, red for enemies.</em></p><h3>Instant Enemy Detection</h3><p>Units used to scan for enemies on a timer, causing a noticeable delay before engaging. Now scanning happens <em>every frame</em> — the moment an enemy enters range, your units open fire.</p><p>But this created a new problem: units that were ordered to retreat would immediately re-acquire the enemies they were running from. The fix is a _move_commanded flag — set when the player issues a move order, cleared when the unit arrives or receives an attack command. While the flag is active, auto-scanning is suppressed. This gives you crisp control over retreats while keeping auto-engage responsive for idle units.</p><h3>Map Layout: Diagonal Opposition</h3><p>The base layout was reorganized into proper SC2-style <strong>diagonal opposition</strong>. On the 32x32 map:</p><ul><li><strong>Player base</strong> (bottom-right): Command Center at tile (24,24), minerals toward the bottom-right map edge, geysers flanking the mineral line</li><li><strong>AI base</strong> (top-left): Command Center at tile (7,7), minerals toward the top-left map edge</li></ul><p>Minerals sit between each base and the nearest corner, acting as a natural wall — just like real SC2 maps. Starting armies are positioned near their respective bases, far enough apart that combat doesn’t begin immediately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gVbG5aTTbWBXCf0qP_ov7w.png" /></figure><p><em>The player base in the bottom-right — Command Center, Barracks, minerals toward the edge, army nearby, Select Army button above the minimap.</em></p><p>The camera boundary system was also tightened to be <strong>zoom-aware</strong>. The camera target clamps based on the current orthographic size, so you can’t pan to show large black areas beyond the map edge regardless of zoom level.</p><h3>Quality of Life</h3><h3>Select All Army (F2)</h3><p>Press F2 or click the <strong>“Select Army”</strong> button above the minimap to instantly select all combat units (Marines, Medics, Siege Tanks) — excluding SCVs. Just like SC2’s army selection hotkey.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*1c_RfLAUYOTf1gmiuiUFRA.gif" /></figure><p><em>The Select Army button above the minimap — one click selects all combat units, ready to move out.</em></p><h3>Better Click Selection</h3><p>Unit selection now targets the <strong>visual center</strong> of units (Y+0.5) rather than their feet (Y=0). With the angled camera, clicking on a unit’s head or body was often too far from the ground-projected position. The selection radius was also slightly increased to 28px for a more forgiving click target.</p><h3>Victory/Defeat Notification</h3><p>The outcome banner moved from a large overlay blocking the center of the screen to a compact notification in the top-right corner. It still tells you to press R to restart, but no longer obscures the battlefield.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*Twridlv5KRStUcFLJXt20g.gif" /></figure><p><em>Full gameplay — SCVs harvesting minerals and gas, army in formation, buildings with HP bars, minimap tracking everything.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*lVReTSllEJpdl5OZMhi80A.gif" /></figure><p><em>Managing the base — training units, selecting the army, sending them across the map toward the enemy.</em></p><h3>What Changed (The Numbers)</h3><p><strong>20 files modified, ~1,370 lines added.</strong> The biggest changes:</p><ul><li>main.gd — +840 lines: command card, info panel, army button, map layout overhaul</li><li>unit_base.gd — +156 lines: instant scanning, move_commanded flag, damage numbers, enhanced combat FX</li><li>selection_manager.gd — +94 lines: HUD rect exclusion, F2 select-all-army, visual-center targeting</li><li>hp_bar_overlay.gd — +78 lines: always-on bars, SC2 colors, HUD occlusion</li><li>siege_tank.gd — +104 lines: turret rotation, stat fixes, barrel-tip firing</li><li>medic.gd — +57 lines: heal beam visualization</li><li>bullet.gd — +45 lines: damage-on-impact, outer glow</li></ul><h3>What’s Next</h3><p>The game is starting to <em>feel</em> right — combat is readable, the HUD is functional, and the map layout makes strategic sense. Next up on the roadmap:</p><ul><li><strong>Phase 11:</strong> SC2 Stat Accuracy Pass — match every stat to real SC2 Faster speed values</li><li><strong>Phase 12:</strong> Gas Economy &amp; Refinery</li><li><strong>Phase 13:</strong> Armor Types &amp; Bonus Damage</li><li><strong>Phase 14:</strong> Splash Damage &amp; Marauder</li></ul><p>We’re closing in on the point where OpenStarCraft isn’t just a tech demo with colored boxes — it’s a playable RTS that happens to use colored boxes.</p><p><em>— Built with Godot 4.6, GDScript, and zero art assets.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=703af25aa5cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building OpenStarCraft from Scratch — Part 4: Going 3D]]></title>
            <link>https://augustdeepthink.medium.com/building-openstarcraft-from-scratch-part-4-going-3d-8d7cb15bc71c?source=rss-310dfdf9c269------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d7cb15bc71c</guid>
            <category><![CDATA[starcraft]]></category>
            <dc:creator><![CDATA[Thinking in AI, Philosophy, Investing, and Mind]]></dc:creator>
            <pubDate>Thu, 12 Mar 2026 16:02:47 GMT</pubDate>
            <atom:updated>2026-03-12T16:02:47.257Z</atom:updated>
            <content:encoded><![CDATA[<p><em>March 12, 2026</em></p><p>In <a href="https://augustdeepthink.medium.com/building-openstarcraft-from-scratch-part-3-building-your-base-dd652bf2929e">Part 3</a>, we got base building, supply depots, factories, and a proper tech tree. The game was playing like a real RTS. But it still <em>looked</em> like a 2D isometric game drawn with colored rectangles. Functional, but flat.</p><p>That changes today. OpenStarCraft is now fully 3D.</p><h3>The Big Rewrite</h3><p>This wasn’t a tweak or a polish pass — it was a ground-up rendering conversion. Every single game object migrated from Node2D to Node3D. Every _draw() method was ripped out and replaced with actual 3D meshes. The entire coordinate system shifted from 2D screen-space to a 3D world with an orthographic camera looking down at the battlefield.</p><p>The scope was enormous: <strong>21 files modified</strong>, over 2,400 lines changed. Here’s what moved:</p><ul><li>All units (Marine, Medic, SCV, Siege Tank, enemies) — now 3D box/sphere meshes</li><li>All buildings (Command Center, Barracks, Factory, Supply Depot, Engineering Bay, Armory) — 3D box meshes with labels</li><li>Mineral patches — glowing 3D crystal shards</li><li>Terrain — MultiMesh ground plane with per-tile coloring</li><li>Fog of war — transparent MultiMesh overlay</li><li>Rocks — 3D box obstacles with height</li></ul><p>But crucially, <strong>none of the game logic changed</strong>. Pathfinding, combat, economy, AI — all of it still runs in 2D tile-space. Only the rendering layer was swapped. The game “thinks” in flat tiles and “draws” in 3D.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3E3ESSlq6DmqhOiHHpOGEQ.png" /></figure><p><em>The full 3D battlefield — rocks, fog of war, minimap, and the isometric camera angle. Placeholder geometry, but unmistakably 3D.</em></p><h3>The Camera</h3><p>Getting the camera right was the most iterated-on piece. StarCraft II uses an orthographic-style camera at a specific angle — steep enough to see the battlefield laid out, but angled enough to see the sides of buildings and give a sense of depth.</p><p>After several rounds of tuning:</p><ul><li><strong>Pitch:</strong> 40° from horizontal — a comfortable middle ground between top-down and side-view</li><li><strong>Yaw:</strong> 45° — the classic isometric rotation that gives buildings that diamond-grid depth</li><li><strong>Projection:</strong> Orthographic, so distant units are the same size as nearby ones (just like SC2)</li></ul><p>And here’s the new feature: <strong>camera rotation</strong>. Hold Shift + Middle Mouse and drag to orbit the camera around the battlefield. Horizontal drag rotates the yaw, vertical drag adjusts the pitch (clamped between 20° and 75° so you can’t flip it upside down). Plain middle-mouse drag still pans as before.</p><p>This alone makes the 3D conversion worth it. Being able to peek around a cliff or rotate to see behind your base adds a whole new dimension to scouting and positioning.</p><h3>Placeholder Geometry</h3><p>We’re still in the “no art assets” phase — everything is colored boxes, spheres, and cylinders. But even with placeholder geometry, the 3D world has real presence:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ga7CWTQQ1K1bBWynuhAp3g.png" /></figure><p>Selection rings are now <strong>torus meshes</strong> — flat green rings that sit on the ground beneath selected units. Combat flashes are translucent spheres that briefly appear on hit or attack. Buildings under construction render at 45% opacity until complete.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JfMnOCgagAP5wA7mEU2Eyw.png" /></figure><p><em>Zoomed in on the player base — Marines in formation, the Barracks with its “BRX” label, Command Center with sensor dish, SCVs harvesting minerals, and a Medic standing by.</em></p><h3>Projectiles</h3><p>The 3D world demanded something the 2D version never had: <strong>visible bullets</strong>.</p><p>When a unit fires, a glowing sphere now streaks from the attacker to the target. The projectile is purely cosmetic — damage is applied instantly (matching SC2’s hitscan behavior for infantry). But the visual feedback makes combat feel dramatically more alive.</p><ul><li><strong>Marine bullets:</strong> tiny yellow spheres, near-instant travel (speed 120)</li><li><strong>Enemy bullets:</strong> red-orange, same speed</li><li><strong>Siege Tank (mobile):</strong> medium yellow-green projectile, moderate speed</li><li><strong>Siege Tank (siege mode):</strong> large orange shell, slow enough to track visually — like watching a real artillery round arc across the field</li></ul><p>Every bullet has emissive material so it glows against the dark ground. They self-destruct on arrival. Simple, but effective.</p><h3>Smooth Group Movement</h3><p>Moving a group of units in the 2D version looked fine — tiles were small on screen and the snap-to-grid movement was barely noticeable. In 3D, with larger tiles and a closer camera, every flaw was magnified.</p><p>Three problems needed solving:</p><h3>Problem 1: Grid Snapping</h3><p>Units marched to tile centers like robots on rails. The fix: pass the <em>exact</em> sub-tile click position as the final destination. The pathfinder still works in tiles for intermediate waypoints, but the last step goes to the precise spot you clicked. Formation members get small offsets from the click point (0.65 tiles apart — just enough to avoid overlap).</p><h3>Problem 2: Corner Oscillation</h3><p>When separation physics pushed a unit near a rock corner, it would bounce: move forward, get pushed into the rock, get ejected back, move forward again — an infinite jitter loop. Three fixes work together:</p><ul><li><strong>Boundary-aware collision:</strong> the walkability check now considers neighboring solid tiles when a unit is near a tile edge</li><li><strong>Waypoint skipping:</strong> if a unit gets pushed past its current waypoint, it skips ahead instead of backtracking</li><li><strong>Wall sliding:</strong> when movement would enter a solid tile, the unit slides along the X or Y axis independently instead of stopping dead</li></ul><h3>Problem 3: Arrival Jitter</h3><p>When a group arrived at their destination, they’d briefly jostle as separation physics fought against their target positions. The old separation was an instant position snap — every frame, overlapping units were teleported apart. Now separation accumulates forces and applies them at a capped speed (4 tiles/sec), so units <em>glide</em> apart smoothly. Combined with formation spacing that matches collision diameter, units arrive at non-overlapping positions and settle instantly.</p><h3>Range-Correct Building Attacks</h3><p>In the 2D version, attack-moving to a building sent your units right up to its doorstep. Marines would walk all the way up and shoot point-blank. Now units respect their attack_range — Marines stop 5 tiles away and fire from distance, Siege Tanks stop at 7 (or 13 in siege mode). If already in range, they don&#39;t move at all.</p><p>This makes base assaults look dramatically better. Your Marines form a firing line at range while Siege Tanks shell from behind. Feels like a real SC2 push.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*BcB7BFUn-frFrhiibj9ZZw.gif" /></figure><p><em>The 3D game in action — units moving, camera panning, the full battlefield alive with placeholder geometry.</em></p><h3>Siege Mode Progress Bar</h3><p>A small but satisfying addition: when a Siege Tank switches between mobile and siege mode, a <strong>blue progress bar</strong> appears beneath the unit during the 3-second transition. It fills from left to right, then disappears when the mode switch completes. In the 2D version, you just had to wait and guess. Now you can see exactly how long until your tank is ready to fire.</p><h3>What Stayed 2D</h3><p>Not everything moved to 3D — and that’s by design. The <strong>HUD layer</strong> stays entirely in 2D, rendered via Godot’s CanvasLayer system on top of the 3D scene:</p><ul><li><strong>Selection box</strong> — still a 2D rectangle drawn in screen space</li><li><strong>Minimap</strong> — reads tile data and draws colored rectangles, plus a camera frustum indicator that now raycasts the 3D viewport corners</li><li><strong>HP bars</strong> — a centralized overlay that projects 3D positions to screen coordinates via camera.unproject_position()</li><li><strong>Resource counter, controls hints, build menus</strong> — all pure 2D text</li></ul><p>This clean separation means the HUD is pixel-perfect regardless of camera angle or zoom level.</p><h3>The Architecture</h3><p>The key insight that made this conversion manageable: <strong>tile-space stays Vector2</strong>. Every unit’s authoritative position (world_pos) is still a 2D float in tile coordinates. Pathfinding, combat ranges, movement speeds, fog of war — all unchanged. The only new math is the rendering conversion:</p><p>Vector3(world_pos.x * 2.0, 0.0, world_pos.y * 2.0)</p><p>That’s it. Every game system operates in the flat tile world. The 3D renderer just multiplies by 2 and swaps Y for Z. This meant the AI controller needed <em>zero functional changes</em> — it was pure game logic with no rendering code.</p><p>The lesson: keep your game logic separate from your rendering, and you can swap the entire visual layer without breaking anything.</p><h3>The Full Controls</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SQ0pcFEKQ0397EnhTdaibA.png" /></figure><h3>What’s Next</h3><p>The game now looks and feels fundamentally different. 3D placeholder geometry, a rotatable camera, visible projectiles, smooth group movement — it’s starting to feel like a real 3D RTS rather than a tech demo.</p><p>But there’s still a long road ahead:</p><ul><li><strong>SC2 stat accuracy pass</strong> — matching every unit’s stats exactly to SC2 Faster speed values</li><li><strong>Gas economy</strong> — Refinery, Vespene Gas, and gas-dependent units</li><li><strong>Armor types and bonus damage</strong> — light vs. armored, concussive vs. explosive</li><li><strong>Sound effects</strong> — the game is still completely silent</li><li><strong>Real 3D models</strong> — eventually replacing these colored boxes with something that actually looks like StarCraft</li></ul><p>But even with boxes and spheres, there’s something magical about watching a squad of blue rectangles march across a green plane, stop at range, and light up a red building with glowing yellow tracers. The game is <em>alive</em>.</p><p><em>OpenStarCraft v0.2.1 — Built with Godot 4.6, GDScript, Claude Code, and the audacity to turn a 2D prototype into a 3D game in one sitting.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d7cb15bc71c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building OpenStarCraft from Scratch — Part 3: Building Your Base]]></title>
            <link>https://augustdeepthink.medium.com/building-openstarcraft-from-scratch-part-3-building-your-base-dd652bf2929e?source=rss-310dfdf9c269------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd652bf2929e</guid>
            <dc:creator><![CDATA[Thinking in AI, Philosophy, Investing, and Mind]]></dc:creator>
            <pubDate>Wed, 11 Mar 2026 19:17:57 GMT</pubDate>
            <atom:updated>2026-03-11T19:19:31.635Z</atom:updated>
            <content:encoded><![CDATA[<p><em>March 11, 2026</em></p><p>In <a href="https://medium.com/@augustdeepthink/building-openstarcraft-from-scratch-part-2-fog-tanks-and-medics-caa947b5ae9d">Part 2</a>, the army got real — Medics healed, Siege Tanks shelled from across the map, and fog of war finally made scouting matter. But there was a glaring problem: all your buildings were pre-placed. You started the game with a Command Center and a Barracks already sitting there, and that was it. No expanding. No choices. No base building.</p><p>That changes today. SCVs can now <em>build</em>.</p><h3>The Build Menu</h3><p>Select an SCV and press B. The bottom bar transforms into a build menu:</p><ul><li>D — <strong>Supply Depot</strong> (100 minerals)</li><li>B — <strong>Barracks</strong> (150 minerals)</li><li>F — <strong>Factory</strong> (200 minerals, requires Barracks)</li></ul><p>Pick one and a <strong>ghost outline</strong> appears under your mouse — green if the tile is valid, red if it’s blocked by rocks or an existing building. Click to place. The SCV immediately walks over and starts hammering away.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iu2B2w5Fu10lA8O0od6zIQ.png" /></figure><p><em>The updated base — note “B: Build” and “V: Tank” in the controls bar, and the dynamic supply counter showing 15/15.</em></p><p>Press Esc or right-click at any time to cancel placement. No minerals wasted.</p><h3>Construction</h3><p>When the SCV reaches the build site, the building appears as a <strong>semi-transparent ghost</strong> with an orange progress bar. The SCV must stay nearby — if you move it away, construction pauses. Move it back (or right-click the unfinished building with another SCV) and it resumes.</p><p>Build times vary:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iqI5uW8Ct2ZQp8ZLdLxtQQ.png" /></figure><p>Once complete, the building snaps to full opacity and becomes functional. A new Barracks can train Marines and Medics. A Factory can produce Siege Tanks. And a Supply Depot quietly does the most important job of all — raising your supply cap.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*WRkcFHsLGAnVrrOWl-Me4g.gif" /></figure><p><em>The full build flow — SCV places a building, walks over, and constructs it from the ground up.</em></p><h3>Supply Depots: Breaking the Cap</h3><p>Up until now, the supply cap was hardcoded at 20. You’d hit it fast, and that was that — no more units. Now supply is <em>dynamic</em>:</p><ul><li><strong>Command Center</strong> provides 15 base supply</li><li>Each <strong>Supply Depot</strong> adds 8 supply</li><li>Maximum cap: 200 (matching the original StarCraft)</li></ul><p>This means your first game decision is already more interesting. Do you rush Marines with your starting 15 supply, or invest 100 minerals in a depot first to unlock a bigger army? Build two depots and you’re at 31 supply — room for a serious force. The economy game just got deeper.</p><p>The Supply Depot itself is a compact green building. Nothing flashy — it’s a box with a vent on top. But every time you see one go up, it means your army is about to grow.</p><h3>The Factory</h3><p>This is the one I was most excited about. The <strong>Factory</strong> is an industrial blue-grey building with a chimney, and it does one thing: produce Siege Tanks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LAyQ8CBRwjjbSp2E82IgpQ.png" /></figure><p>To build a Factory, you need a completed Barracks — just like the real StarCraft tech tree. This creates a natural progression:</p><ol><li>Command Center (start) → harvest minerals</li><li>Barracks (150m) → Marines, Medics</li><li>Supply Depot (100m) → more army room</li><li>Factory (200m) → Siege Tanks</li></ol><p>Before this update, the starting Siege Tank just spawned for free. Now you have to <em>earn</em> it. Build a Barracks, then a Factory, then invest 150 minerals and 25 seconds. When that first tank rolls off the production line, it feels so much more rewarding.</p><p>Select the Factory and you get the same production panel as the Barracks — queue up to 5 tanks, watch the progress bar fill, see the queue counter. The panel title dynamically switches between “BARRACKS” and “FACTORY” depending on what’s selected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*_pOmBdSIWgC4GK9rF1Qqmw.gif" /></figure><p><em>A growing base — Barracks, minerals, Command Center, and the full army roster.</em></p><h3>Under the Hood</h3><p>A few technical details that made this work:</p><h3>Ghost Preview</h3><p>The build ghost is a lightweight Node2D that lives in the game world and repositions itself every frame to the tile under the mouse cursor. It converts screen coordinates → world coordinates → tile coordinates, then snaps to the tile center. The color shifts between green and red based on is_walkable().</p><h3>Construction State Machine</h3><p>Every building now has a constructing flag and a build_progress float (0.0 → 1.0). While constructing, the building draws at 45% opacity and shows an orange progress bar instead of the HP bar. Production is disabled until construction completes.</p><h3>SCV Build States</h3><p>The SCV state machine grew two new states: MOVE_TO_BUILD and BUILDING. Since buildings occupy non-walkable tiles, the SCV pathfinds to the nearest adjacent walkable tile, then starts calling advance_construction() every frame. When the building completes, the SCV goes idle.</p><h3>Input Priority</h3><p>Build mode disables the selection manager’s input processing so clicks go to building placement instead of unit selection. When build mode exits, selection resumes normally. Clean separation — no hacks needed.</p><h3>Multiple Barracks</h3><p>One subtle but powerful consequence of building construction: you can now build <strong>multiple Barracks</strong>. Two Barracks means double the Marine production. Three means triple. Each one has its own independent production queue and rally point.</p><p>The same goes for Factories. Want a tank rush? Build two Factories and pump out Siege Tanks twice as fast. The strategic options are multiplying.</p><h3>The Full Controls</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YvvSk1CzdAFWSpoml2sHBA.png" /></figure><h3>What’s Next</h3><p>With building construction in place, the game finally has a real progression arc. You start with a base, harvest minerals, build structures, produce units, and push out to fight. It feels like an actual RTS now.</p><p>But we’re still missing some big pieces:</p><ul><li><strong>Upgrades</strong> — weapon and armor research at an Engineering Bay</li><li><strong>Tech tree</strong> — proper dependencies between buildings</li><li><strong>AI opponent</strong> — a computer player that builds and attacks on its own</li><li><strong>Audio</strong> — sound effects, voice lines, music</li></ul><p>The next phase will probably be upgrades and the tech tree — giving your army the ability to grow stronger over time, not just bigger. Stay tuned.</p><p><em>OpenStarCraft v0.1.8 — Built with Godot 4.6, GDScript, Claude Code, and a dream of recreating the greatest RTS ever made.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd652bf2929e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>