<?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 Sualp oven on Medium]]></title>
        <description><![CDATA[Stories by Sualp oven on Medium]]></description>
        <link>https://medium.com/@sualpoven2?source=rss-357de6e6cc75------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*2R4JOYr7ahJ2LPIi</url>
            <title>Stories by Sualp oven on Medium</title>
            <link>https://medium.com/@sualpoven2?source=rss-357de6e6cc75------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 16:07:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sualpoven2/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[I Built an AI Dodgeball Opponent That Learns to Beat You — Using Reinforcement Learning in Unity]]></title>
            <link>https://medium.com/@sualpoven2/i-built-an-ai-dodgeball-opponent-that-learns-to-beat-you-using-reinforcement-learning-in-unity-921951fdc923?source=rss-357de6e6cc75------2</link>
            <guid isPermaLink="false">https://medium.com/p/921951fdc923</guid>
            <dc:creator><![CDATA[Sualp oven]]></dc:creator>
            <pubDate>Sat, 13 Jun 2026 18:44:26 GMT</pubDate>
            <atom:updated>2026-06-23T20:06:06.625Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How I used Unity ML-Agents, POCA, and Self-Play to create an adaptive AI that actually improves your aim training</em></p><p>Every serious FPS player has opened Aim Lab at some point. You boot it up, pick a scenario, and grind for thirty minutes. The targets pop up in patterns, you click them, your accuracy number ticks up. It feels productive. You feel like you’re getting better.</p><p>Then you go back into your actual game, and you miss shots you should hit.</p><p><strong>Why?</strong></p><p>Because the bots you practiced on were scripted. They moved in predetermined arcs. They appeared at predictable intervals. Your brain didn’t learn to aim — it learned the <em>pattern</em>. And real opponents don’t have patterns. Real opponents adapt. Real opponents punish you for being predictable.</p><p>This is the problem I wanted to solve. Not by making a better scripted bot — but by using <strong>Reinforcement Learning</strong> to create an AI opponent that genuinely <em>learns</em>, adapts, and over time becomes a training partner that forces you to get better because it’s getting better too. The final result isn’t just a strong AI — it’s an <strong>adaptive</strong> one that reads your current skill level and calibrates its intensity accordingly: easy enough not to discourage beginners, hard enough to genuinely challenge experienced players.</p><p>This is the story of how I built it.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FMdGqb53Cxhs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DMdGqb53Cxhs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FMdGqb53Cxhs%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/78a1f4835ca52c5df75f7debad52c109/href">https://medium.com/media/78a1f4835ca52c5df75f7debad52c109/href</a></iframe><h3>The Core Problem : Why Scripted Bots Plateau Your Skill</h3><p>Let me be precise about what’s wrong with conventional aim trainers.</p><p>Aim Lab, KovaaK’s, and similar tools use <strong>rule-based or scripted movement systems</strong>. A target appears, moves along a pre-programmed trajectory, and disappears when clicked. The developers tune these trajectories to feel smooth and satisfying to track. They add variance — some targets move faster, some in curved paths — but fundamentally, every movement is authored by a human programmer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4ncISLrr4cE3hVFn" /><figcaption>Credit : KovaaK on steam</figcaption></figure><p>This creates a well-known phenomenon in motor learning called <strong>pattern overfitting</strong>. Your motor system — the part of your brain that handles aim — is extraordinarily good at recognizing and exploiting patterns. Within a few hundred repetitions, it has internalized the timing, rhythm, and spatial boundaries of the scenario. You’re no longer reacting to a moving target; you’re executing a memorized motor program.</p><p>The moment you enter a real match against a human opponent who moves unpredictably, that motor program fails. The movement falls outside the distribution you trained on. Your aim feels broken not because your mechanics degraded — but because your practiced mechanics never generalized.</p><p>The fix is obvious in principle : <strong>your training opponent needs to be as unpredictable as a human</strong>. Not scripted-random (uniform random movement is actually very easy to track because it has no coherent strategy), but <em>strategically</em> unpredictable — moving in ways that serve a goal, creating genuine reaction-time demands and spatial uncertainty.</p><p>The only scalable way to achieve this is <strong>machine learning</strong>.</p><h3>What Is Machine Learning, Really?</h3><p>Before we go further, it’s worth grounding the term — because “machine learning” gets thrown around so loosely that it starts to lose meaning.</p><p>At its core, <strong>machine learning is the practice of letting a computer learn from experience rather than from explicit instructions.</strong> In traditional programming, a developer writes rules: <em>if the enemy is to the left, move right; if the player throws a ball, dodge.</em> Every behavior is manually authored. The program does exactly what the programmer anticipated — nothing more.</p><p>Machine learning flips this. Instead of writing rules, you define a <strong>goal</strong> (win the round) and a way to measure progress toward it (the reward signal). The algorithm then explores the space of possible behaviors on its own, reinforcing actions that lead to the goal and discarding ones that don’t. The rules emerge from experience — they are never written by hand.</p><p>This is done through a <strong>neural network </strong>: a mathematical function loosely inspired by how neurons connect in the brain. At its simplest, a neural network takes inputs (what the agent currently observes), passes them through layers of weighted connections, and produces outputs (what action to take). The “learning” part is the process of adjusting those weights — millions of tiny nudges over millions of interactions — until the network’s outputs reliably produce good outcomes.</p><p>In this project specifically, the flavor of machine learning used is <strong>Reinforcement Learning (RL)</strong>. Unlike supervised learning (which learns from labeled examples) or unsupervised learning (which finds patterns in raw data), RL learns from <strong>interaction</strong>. The agent acts, observes the consequence, receives a reward or penalty, and updates its behavior accordingly. No human ever demonstrates the correct move. No dataset of expert play is provided. The agent discovers what works entirely on its own by trying things and seeing what happens.</p><p>This distinction matters for the aim training use case : because the agent’s strategies emerge from self-play rather than from human-authored rules or human demonstration data, they can be genuinely surprising — and genuinely difficult to predict. Which is exactly what a useful training opponent needs to be.</p><h3>Why Reinforcement Learning? The Case for RL Over Alternatives</h3><p>Before committing to RL, I considered the alternatives.</p><p><strong>Imitation Learning</strong> (having AI learn from recordings of human players) sounds appealing but has a critical flaw : it caps at the skill level of the humans in the dataset. If I recorded myself playing, the AI would learn to move like <em>me</em>, which means it would be trivially predictable to me.</p><p><strong>Handcrafted AI with randomized parameters</strong> is what most commercial games do. A behavior tree with randomized reaction times, inaccuracy spreads, and movement patterns. This scales better than scripted bots but still suffers from the same fundamental problem : a human designed the strategy space. The AI can only be as creative as its programmer.</p><p><strong>Reinforcement Learning with Self-Play</strong> sidesteps both problems entirely. The AI discovers its own strategies by playing against itself, starting from nothing and bootstrapping toward increasingly sophisticated behavior. Nobody told it to sidestep before throwing. Nobody told it to feint. It figures out that these behaviors increase its probability of winning, and it does them. The strategies are emergent, not authored.</p><p>More importantly, Self-Play RL produces an AI whose difficulty scales naturally with its training time. At 500,000 steps it’s a beginner. At 10 million steps it’s an expert. You get a continuous spectrum of opponents from a single training run — which maps perfectly onto a tiered aim training system.</p><p>Now the obvious question: <strong>how do we actually know if any of this is working?</strong></p><h3>Metrics and Baselines : How Do We Know If It’s Working?</h3><p>Before training a single step, we need to define what “working” actually means — and what we’re comparing against. This section covers both : the metrics used to evaluate the AI, and what others have achieved in similar environments.</p><h4>The Four Metrics</h4><p><strong>ELO Rating</strong> is the primary metric throughout this project. Originally developed for chess rankings, ELO measures relative skill between two competitors. The difference in ELO between two players predicts match outcomes — a player at ELO 2100 versus one at 1800 implies roughly an 85% win probability for the higher-rated player. In ML-Agents self-play, both agents start at ELO 1,200 and update after every match. A continuously rising ELO curve confirms the agent is genuinely improving, not just getting lucky. This is the single most important number to watch during training.</p><p><strong>Hit Rate</strong> measures the percentage of throws that actually connect with the opponent. An untrained agent throwing randomly achieves roughly 5% — barely above chance. This metric directly reflects aim quality and is the most meaningful number from an aim training perspective : it tells us whether the AI is actually practicing a skill the human player needs to react to.</p><p><strong>Episode Reward</strong> is the cumulative reward earned per round of play. Since the reward function rewards hits (+0.1 each) and wins (+2.0), a rising episode reward signals that the agent is developing both accurate throwing and round-winning strategy simultaneously. It’s the training signal the neural network directly optimizes.</p><p><strong>Steps to Win</strong> measures how many timesteps elapse before an agent wins a round. A decreasing number here means the agent is playing more decisively — not just winning, but winning <em>faster</em>. This correlates with more aggressive, skillful play, and matters for the human player because it means the AI creates pressure rather than passive exchanges.</p><h4>What Others Have Done : Published Baselines</h4><p>This project builds directly on Unity’s official DodgeBall environment. Unity’s own engineering team published results on the original 4v4 version using MA-POCA combined with self-play :</p><blockquote>Agents eventually play at a level comparable to human testers — but this required <strong>tens of millions of training steps</strong>. Early training (0–40M steps) produces agents that learn to shoot but with poor aim and random movement. After 40M steps, aim improves but movement remains somewhat random. After 120M total steps, agents become aggressive and develop coordinated team strategies like charging enemy territory as a group. — Unity Blog, “ML-Agents plays DodgeBall” (2021)</blockquote><p>For multi-agent competitive environments more broadly, researchers at UCLA (CS269, Fall 2022) compared PPO, POCA, and SAC on a 2v2 soccer game in Unity and found that <strong>POCA outperformed PPO in final ELO score</strong>, suggesting POCA agents develop higher skill in cooperative-competitive settings. SAC was found impractical for self-play because the constantly-changing opponent creates non-stationary dynamics that break SAC’s experience replay mechanism — which is why the ML-Agents documentation explicitly recommends PPO or POCA for self-play training.</p><p>A study on ML-Agents for autonomous driving (MDPI, 2023) confirmed that PPO yielded the best results among tested algorithms, achieving a value loss of 0.0013 and cumulative reward of 0.761 — reinforcing PPO’s reputation as the most stable baseline across Unity simulation environments.</p><h3>How This Project Compares</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pRqG4TuGKOMFSO5yxmpQ1Q.png" /><figcaption>Table compare ML agents</figcaption></figure><p>The critical insight here: <strong>1v1 needs dramatically fewer training steps than team-based environments.</strong> The original 4v4 DodgeBall requires 40–120 million steps for competent behavior because agents must learn both individual skill <em>and</em> team coordination simultaneously. By stripping to 1v1, the coordination problem disappears entirely. This project reached peak ELO ~1,600 in Stage 2, which represents a solid intermediate-to-advanced skill level against the published baselines above.</p><h3>The Environment : From 4v4 Dodgeball to 1v1 Aim Trainer</h3><p>I started with the <strong>Unity ML-Agents DodgeBall</strong> example environment. This is an open-source 4v4 dodgeball game built specifically for ML training — it has physics-based ball throwing, agent movement, team scores, and a pre-wired ML-Agents integration. It’s a solid foundation, but 4v4 is too chaotic for aim training purposes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XfewgTx4jaXkY3Zb.png" /><figcaption>Unity Dodgeball in game.</figcaption></figure><p>The first major transformation was reducing it to <strong>1v1</strong>.</p><p><strong>This required :</strong></p><ul><li>Deleting 3 agents from BlueTeam and PurpleTeam in the scene hierarchy, leaving exactly one of each</li><li>Trimming the serialized Team0Players and Team1Players lists on DodgeBallGameController to single entries</li><li>Reducing NumberOfBallsToSpawn from 10 down to <strong>4</strong> — fewer balls means the AI is forced to aim carefully rather than spam throws</li><li>Shrinking the arena scale to <strong>0.6x</strong> — smaller arena accelerates encounters, generating more training data per episode and forcing the agents into closer-range engagements where aim precision matters</li></ul><p>Smaller arena + fewer balls + 1v1 = high-intensity, aim-critical encounters every episode. Exactly what we want.</p><h4>Environment Parameters at a Glance</h4><p>This section we will talk about what are we going to modify Environment Parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YRzut10NP8pn52JR3aotHA.png" /><figcaption>Environment Parameters</figcaption></figure><p><em>The stun mechanic deserves special mention. Ten seconds of stun in an 83-second episode is enormous — it’s essentially losing 12% of your round window whenever you get hit. This creates strong incentive for the AI to learn to dodge, not just aim, which is exactly the dual-threat behavior we want in a training opponent.</em></p><p>Now, that you know briefly what we need to modify, in the next section I will guide you step by step until you can start training your own RL agent!</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DGPhIeLq2JaM&amp;type=text%2Fhtml&amp;schema=youtube&amp;display_name=YouTube&amp;src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FGPhIeLq2JaM%3Ffeature%3Doembed" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/271b83039b3a73e33a7cafeabe1e514a/href">https://medium.com/media/271b83039b3a73e33a7cafeabe1e514a/href</a></iframe><h3>Setting Up : How to Reproduce This From Scratch</h3><p>This section walks through the complete environment setup — everything I had to figure out through trial and error so you don’t have to.</p><h4>Prerequisites</h4><ul><li><strong>Unity 6.3 LTS (6000.3.11f1) </strong><em>Note that any Unity 6 version should work fine.</em></li><li><strong>Visual Studio 2022 </strong>This is my personal preference, as it is much easier to debug for me and it can use <strong>terminal</strong> in Visual Studio 2022 to import and download.</li><li><strong>Python 3.10.x</strong> specifically — mlagents 1.1.0 does not work with Python 3.11+ or 3.12 due to cattr dependency conflicts</li><li><strong>CUDA-compatible GPU</strong> recommended (RTX 3000 series or later); CPU training is possible but very slow</li><li><strong>Git</strong> for cloning the ML-Agents DodgeBall repository</li></ul><h3><strong>Now let’s get started</strong></h3><h4>Step 1 — Install Python 3.10</h4><p>If you already have a different Python version (e.g. 3.12 or 3.14), <strong>do not uninstall it</strong>. Install Python 3.10 alongside it using the direct installer from python.org. On Windows, this lets you call it specifically with py -3.10 while your default python remains unchanged.</p><p>Verify the install in the terminal :</p><pre>py -3.10 --version<br># Should output: Python 3.10.x</pre><h4>Step 2 — Install PyTorch with CUDA</h4><p>Use the CUDA 12.4 index URL to get the GPU-accelerated build in the terminal :</p><pre>py -3.10 -m pip install torch==2.5.1 --index-url https://download.pytorch.org/whl/cu124</pre><p><strong>Verify GPU is detected </strong>in<strong> </strong>the terminal <strong>:</strong></p><pre>py -3.10 -c &quot;import torch; print(torch.cuda.is_available())&quot;<br># Should output: True</pre><p>If you see False, your CUDA drivers are outdated — update via NVIDIA GeForce Experience or the NVIDIA driver download page.</p><h4>Step 3 — Install ML-Agents in the terminal</h4><pre>py -3.10 -m pip install mlagents==1.1.0</pre><p>⚠️ <strong>Important </strong>: Do NOT use pip install mlagents without specifying the version. The latest release may have different dependencies. Version 1.1.0 is confirmed working with PyTorch 2.5.1 + CUDA 12.4.</p><h4>Step 4 — Clone and Modify the DodgeBall Environment</h4><p>Clone Unity’s official DodgeBall repository :</p><pre>git clone https://github.com/Unity-Technologies/ml-agents-dodgeball-env.git</pre><p>Open the project in Unity. Head to Scenes Folder and Find “Elimination_Training” and copy this scene just in case if there is a problem it will much easier to fix. Then make the following modifications to convert 4v4 → 1v1 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*i8sK3HKWqEQ3yFn1qZxzgQ.png" /><figcaption>Elimination_Training Scene Hierarchy</figcaption></figure><p><strong>In the Unity Scene Hierarchy :</strong></p><ol><li>Expand BlueTeam — delete 3 of the 4 agents, keep only 1</li><li>Expand PurpleTeam — delete 3 of the 4 agents, keep only 1</li></ol><p><strong>In </strong><strong>DodgeBallGameController.cs</strong>, find the two hardcoded team size references and update them :</p><pre>// Change this:<br>m_NumberOfBluePlayersRemaining = 4;<br>m_NumberOfPurplePlayersRemaining = 4;<br><br>// To this:<br>m_NumberOfBluePlayersRemaining = 1;<br>m_NumberOfPurplePlayersRemaining = 1;</pre><p>Also update the serialized player lists in the Inspector — select DodgeBallGameController in the hierarchy, and trim Team0Players and Team1Players to contain only 1 agent each.</p><p><strong>Reduce arena size </strong>: Select the Arena GameObject and set Scale to (0.6, 1, 0.6).</p><p><strong>Reduce ball count </strong>: On DodgeBallGameController, set NumberOfBallsToSpawn from 10 to 4.</p><h4>Step 5 — Create the Training Config</h4><p>Create a file dodgeball_1v1.yaml in new config folder :</p><pre>behaviors:<br>  DodgeBall:<br>    trainer_type: poca<br>    hyperparameters:<br>      batch_size: 2048<br>      buffer_size: 20480<br>      learning_rate: 0.0003<br>      beta: 0.005<br>      epsilon: 0.2<br>      lambd: 0.95<br>      num_epoch: 3<br>      learning_rate_schedule: constant<br>    network_settings:<br>      normalize: false<br>      hidden_units: 512<br>      num_layers: 3<br>      vis_encode_type: simple<br>      goal_conditioning_type: none<br>    reward_signals:<br>      extrinsic:<br>        gamma: 0.999<br>        strength: 1.0<br>    keep_checkpoints: 40<br>    checkpoint_interval: 2000000<br>    max_steps: 50000000<br>    time_horizon: 1000<br>    summary_freq: 50000<br>    threaded: false<br>    self_play:<br>      save_steps: 500000<br>      team_change: 1000000<br>      swap_steps: 200000<br>      window: 10<br>      play_against_latest_model_ratio: 0.5<br>      initial_elo: 1200.0</pre><p><em>⚠️ </em><strong><em>Critical self-play note </em></strong><em>: Keep </em><em>window: 10. Using the default </em><em>window: 100 causes severe ELO crashes when you resume training because the agent gets matched against opponents from past. that it has no chance against. </em><em>window: 10 keeps the opponent pool recent and training stable across resumes.</em></p><h4>Step 6 — Start Training</h4><p>Open Unity with the DodgeBall scene loaded. Then in a terminal in Visual Studio 2022, run :</p><pre>py -3.10 -c &quot;from mlagents.trainers.learn import main; main()&quot; &quot;config/dodgeball_1v1.yaml&quot; --run-id=dodgeball_1v1_v1</pre><p><em>⚠️ </em><strong><em>Why this command instead of </em></strong><strong><em>mlagents-learn?</em></strong><em> On Windows with multiple Python versions, </em><em>mlagents-learn often resolves to the wrong Python installation. The </em><em>-c &quot;from mlagents.trainers.learn import main; main()&quot; pattern forces it to use exactly Python 3.10 every time.</em></p><p>After that in the terminal you will see text “Listening on port 5004” Once you see that message, head back to the Unity Editor and press Play in order to start training.</p><p>Now, you should see Unity start, the agents spawn in the arena, and TensorBoard stats begin appearing in results/dodgeball_1v1_v1/. Training has started successfully when you see step counts incrementing in the terminal.</p><h4>Step 7 — Monitor the progress</h4><p>Look in Visual Studio 2022 terminal, It will show how many steps our agent has already completed and it will show what is the reward and ELO level.</p><h4>Step 8 — Resume After Interruption</h4><p>If training is interrupted (crash, power loss, or intentional stop), resume with :</p><pre>py -3.10 -c &quot;from mlagents.trainers.learn import main; main()&quot; config/dodgeball_1v1.yaml --run-id=dodgeball_1v1_v1 --resume</pre><p><em>⚠️ </em><strong><em>Always stop Unity before pressing Ctrl + C in the terminal.</em></strong><em> Stopping the terminal first can corrupt the checkpoint files. The safe sequence is : pause Unity → Ctrl+C in terminal → close Unity.</em></p><h3>Observation Space : What the AI Sees</h3><p>Every timestep (every 5 Unity FixedUpdate ticks), each agent receives an observation vector describing the current game state. This is the AI’s entire perception of the world — it sees nothing else.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*AipKxPhdtBuZudKw7Zdm1w.png" /><figcaption>How AI using ray cast to see things in the game</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*wgnYPvhIvwVvsaKQeLQ04A.png" /><figcaption>Most of ML agent’s action in game</figcaption></figure><p>Every positional value is <strong>normalized</strong> — divided by a LocationNormalizationFactor of 80.0 — so all values fall in the range [-1, 1]. This is the RL equivalent of feature scaling in supervised learning: it prevents large-magnitude values from dominating gradient updates and keeps training stable.</p><h3>Observation Space : 22 Inputs</h3><p>In the adaptive difficulty version of this project, two additional observations were added beyond the original 20 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*FKCKnUl8HLMJsKi6F1BjpQ.png" /></figure><p>These two new observations allow the AI to read the human player’s current skill level and adjust its behavior accordingly — which is the foundation of the adaptive difficulty system described later.</p><pre>// Added at the end of CollectObservations()<br>sensor.AddObservation(playerMetrics != null ? playerMetrics.currentWinRate : 0.5f);<br>sensor.AddObservation(playerMetrics != null ? playerMetrics.currentHitAccuracy : 0.5f);</pre><p>This design is deliberately minimal. The agent has no global map. It doesn’t see the opponent’s velocity directly — it has to infer movement from relative position changes across timesteps. This partial observability forces the AI to develop <em>predictive</em> behavior rather than simply reacting to perfect information.</p><h3>Reward Function Design : Teaching the AI What to Care About</h3><p>The reward function is the most critical design decision in any RL project. It’s how you communicate your goals to the AI — not through code logic, but through a signal that it optimizes over millions of interactions.</p><p>Getting it wrong is easy. Get the rewards even slightly unbalanced and the AI finds degenerate strategies : hide in a corner, spam throws randomly, refuse to engage. These behaviors can maximize reward while completely failing to produce the useful training partner we want.</p><p>Here’s the reward structure that remain unchanged from the original I settled on :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MAg46XiufdyD7xDByGY4uw.png" /></figure><p>The time_bonus in the win reward is a subtle but important detail. It means winning in 30 seconds is worth more than winning in 80 seconds. This creates pressure to play aggressively, which is exactly the kind of behavior that makes for a challenging training opponent.</p><p>The zero reward for holding balls is equally deliberate. An early version of the reward function gave a tiny positive reward for having balls in hand (thinking it would encourage ball retrieval). Instead, the AI learned to pick up balls and never throw them — a perfect reward hack. Zero reward for holding forces the AI to derive value only from <em>using</em> the balls.</p><h4>Adaptive Reward : Teaching the AI to Scale Difficulty</h4><p>Beyond the base rewards, an <strong>adaptive reward signal</strong> was added to teach the AI to modulate its aggression based on who it’s playing against :</p><pre>if (playerMetrics != null)<br>{<br>    float winRate = playerMetrics.currentWinRate;<br>    float accuracy = playerMetrics.currentHitAccuracy;<br>    float skillScore = (winRate + accuracy) / 2f;<br><br>    // Smooth skill-based reward using Lerp<br>    float adaptiveReward = Mathf.Lerp(-1.0f, 1.5f, skillScore);<br>    AddReward(adaptiveReward);<br>}</pre><p>This Lerp-based approach produces a <strong>smooth, continuous reward gradient</strong> rather than abrupt jumps between difficulty levels:</p><ul><li><strong>Newbie</strong> (skillScore &lt; 0.33) : Adaptive reward ~-1.0 — penalizes the AI for destroying beginners too quickly, nudging it toward restraint</li><li><strong>Medium</strong> (skillScore 0.33–0.66) : Adaptive reward ~+0.25 — normal play</li><li><strong>Pro</strong> (skillScore &gt; 0.66) : Adaptive reward ~+1.5 — rewards aggressive, full-strength play</li></ul><h4>What the AI Is NOT Rewarded For</h4><p><strong>Just as important :</strong> the AI gets no reward for spatial positioning, for facing the opponent, for “looking threatening,” or for any proxy behavior. Every reward comes from outcomes — hits and wins. This forces genuine skill development rather than superficial performance.</p><h3>Exploratory Data Analysis : Understanding the Training Dynamics</h3><p>In supervised learning, EDA means analyzing your dataset. In RL, there is no dataset at the start — so EDA means analyzing the <strong>environment design</strong> and <strong>reward landscape</strong> before committing to a training run.</p><p>This upfront analysis is critical. Mistakes discovered after 10 million training steps cost days of compute time.</p><h3>Action Space Analysis</h3><p>Before designing the reward, it’s worth understanding what the agent can actually <em>do</em> — its action space defines the vocabulary of possible behaviors.</p><p>The DodgeBall agent has a <strong>mixed action space</strong> combining continuous and discrete actions simultaneously :</p><p><strong>Continuous actions</strong> (output as mean μ and log std σ of a Gaussian distribution) :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*okiyCZlOofPGepDdgjQiWA.png" /></figure><p><strong>Discrete actions</strong> (output as categorical logits) :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*pYU7CC4zRyc6ufLJUscRPA.png" /></figure><p>This mixed space is important for understanding why POCA+PPO is the right algorithm here. The continuous movement actions require a policy that outputs probability distributions (Gaussian), while the discrete throw/dash decisions require categorical outputs. PPO handles both natively in a single forward pass — many other algorithms, including SAC, cannot handle this mixed space as cleanly.</p><p>The practical consequence : the agent can simultaneously move, rotate, <strong>and</strong> decide to throw within a single timestep. This means skillful play involves coordinating all five action dimensions at once — strafing while rotating to track the opponent while timing a throw. An untrained agent samples these five dimensions independently at random, which is why early training looks chaotic: the agent is stumbling through a 5-dimensional action space with no sense of which combinations lead to reward.</p><p>The size of the action space also explains why RL is necessary. A rule-based system would need to enumerate every meaningful combination of movement + rotation + throw timing and assign a behavior to each. RL discovers the good combinations automatically through millions of interactions — no enumeration required.</p><h3>Reward Signal Analysis</h3><p>Before training, I worked through the reward function mathematically to check for incentive alignment.</p><pre>Passive agent (never throws):<br>  0.0 (holding balls) − 1.0 (losing) = −1.0 per episode<br><br>Aggressive agent (5 hits + fast win):<br>  5 × 0.1 (hits) + 2.0 − 0.1 (time_bonus) = +2.4 per episode<br><br>Gap: +3.4 reward units in favor of aggressive play</pre><p>A gap of 3.4 units is large enough that the optimizer will reliably discover aggression as the dominant strategy. The incentive structure is clean.</p><h3>Episode Length Analysis</h3><p>At 5,000 max steps with 5 FixedUpdate ticks per timestep, one episode is approximately 83 seconds at real-time speed. However, during ML-Agents training, Unity runs at <strong>accelerated simulation speed</strong> — up to 20× real time — so those 83 seconds of game time take about 4 seconds of wall clock time. The full training run is configured for <strong>50 million steps</strong> (max_steps: 50000000), which would take roughly 24–30 hours on this hardware (Ryzen 9800X3D + RTX 4070 Ti Super), though the best result of ELO ~1,600 was achieved at just 25M steps — well before the full budget was consumed.</p><h3>Expected ELO Progression</h3><p>ELO is used in Self-Play RL as a continuous measure of agent capability. It starts around 1,200 (the conventional base) and increases as the agent wins against increasingly capable versions of itself. Based on this project’s actual training results across three stages :</p><pre>Stage 1 (0–2M steps)<br>  Steps 0       →  ELO ~1200   (random behavior — stationary target only)<br>  Steps 2M      →  ELO ~1350   (basic throwing and ball pickup learned)<br><br>Stage 2 (2M–25M steps — Peak ELO)<br>  Steps 5M      →  ELO ~1450   (begins tracking moving targets)<br>  Steps 10M     →  ELO ~1550   (consistent aim + basic dodging)<br>  Steps 25M     →  ELO ~1600   (integrated aim + evasion — Stage 2 peak)<br><br>Stage 3 (25M–35M steps — Adaptive Curriculum)<br>  ELO ~1150–1200 (intentional drop — AI holds back against simulated beginners)</pre><p>The jump from 1500 to 1600 — where dodging and aiming start happening simultaneously — is the critical threshold for a genuinely useful training opponent. Below it, the AI aims but stands still. Above it, the AI actively creates angles and dodges while attacking.</p><p>The Stage 3 ELO drop is not a failure — it is proof the adaptive system is working. The AI is deliberately restraining itself against simulated novice opponents during curriculum training.</p><h3>The Model : Proximal Policy Optimization with MA-POCA</h3><p>The algorithm doing the actual learning is <strong>MA-POCA</strong> (Multi-Agent Posthumous Credit Assignment), Unity ML-Agents’ cooperative multi-agent algorithm, running with a PPO optimizer underneath. While this is technically a 1v1 competitive environment rather than a cooperative one, POCA was chosen over vanilla PPO based on the published evidence that POCA consistently achieves higher ELO in team-based Unity environments.</p><h4>Part 1 : The Foundation — Proximal Policy Optimization (PPO)</h4><p>Before understanding POCA, we need to understand PPO, because POCA builds directly on top of it.</p><p>Reinforcement Learning’s goal is to find a policy π(a|s) — a function that maps states to actions — that maximizes expected cumulative reward :</p><p><strong>J(θ) = E_π [ Σ γᵗ rₜ ]</strong></p><p>Where θ are the policy parameters (neural network weights), <strong>γ</strong> is the discount factor (0.999 in this project), and <strong>rₜ</strong> is the reward at timestep <strong>t</strong>.</p><p>The naive way to optimize this is vanilla Policy Gradient, which updates parameters in the direction that increases the probability of actions that led to high reward :</p><p><strong>∇J(θ) = E_π [ ∇ log π_θ(aₜ|sₜ) · Aₜ ]</strong></p><p>Where Aₜ is the <strong>advantage</strong> — how much better action aₜ was compared to the average action at state sₜ. The problem with this : a single bad gradient update can collapse the policy completely, because there’s no limit on how much the policy can change in one step.</p><p><strong>PPO solves this with a clipping constraint.</strong> Instead of directly maximizing the policy gradient, PPO maximizes a clipped surrogate objective :</p><p><strong>L_CLIP(θ) = E [ min( rₜ(θ) · Aₜ , clip(rₜ(θ), 1-ε, 1+ε) · Aₜ ) ]</strong></p><p>Where :</p><ul><li>rₜ(θ) = π_θ(aₜ|sₜ) / π_θ_old(aₜ|sₜ) is the probability ratio between new and old policy</li><li>ε = 0.2 (our config) is the clip range — policy can&#39;t change by more than 20% in one update</li><li>Aₜ is the advantage estimate</li></ul><p>The min() and clip() together act as a seatbelt : if an update would push the policy too far in either direction, it gets clipped at the boundary. This makes training dramatically more stable than vanilla Policy Gradient, which is why PPO became the standard algorithm for game AI.</p><p><strong>Advantage Estimation with GAE</strong></p><p>The advantage Aₜ is estimated using <strong>Generalized Advantage Estimation (GAE) </strong>:</p><p><strong>Aₜ = Σₗ (γλ)ˡ δₜ₊ₗ</strong></p><p>Where the TD residual at each step is :</p><p><strong>δₜ = rₜ + γ · V(sₜ₊₁) — V(sₜ)</strong></p><p>And V(s) is the value function (estimated by the Critic network). In this config :</p><ul><li>γ = 0.999 — near-zero discounting, agent values future rewards almost as much as immediate ones</li><li>λ = 0.95 — controls bias-variance tradeoff in the advantage estimate; 0.95 gives low variance without introducing too much bias from the value function approximation</li></ul><p>The entropy bonus term is also added to prevent premature convergence :</p><p><strong>L_TOTAL = L_CLIP — β · H[π_θ(·|sₜ)]</strong></p><p>Where H is the policy entropy and β = 0.005 (our config). This keeps the policy exploring rather than collapsing to a deterministic strategy too early.</p><h4><strong>Part 2 : Why PPO Alone Is Not Enough — The Credit Assignment Problem</strong></h4><p>PPO works well for single agents. But in a game where <strong>a sequence of actions over 1,000 timesteps</strong> leads to a win, there is a fundamental problem : which of those 1,000 actions actually caused the win?</p><p>If an agent throws a ball at step 200, and that throw eventually stuns the opponent and leads to a win at step 800, PPO must propagate the win reward backward through 600 timesteps of discounting. Even with γ = 0.999, that signal is multiplied by 0.999⁶⁰⁰ ≈ 0.549 by the time it reaches step 200. The early throw gets only 55% of the credit it deserves. Deeper into training, this credit starvation causes the agent to undervalue early aggressive plays and over-index on actions close in time to the reward signal.</p><p>This is the <strong>temporal credit assignment problem</strong>, and it gets worse as episode length increases.</p><h4><strong>Part 3 : MA-POCA — Posthumous Credit Assignment</strong></h4><p><strong>MA-POCA</strong> (Multi-Agent POsthumous Credit Assignment) extends PPO with a centralized critic architecture designed specifically to solve this problem in multi-agent settings.</p><p>The key innovation is a <strong>counterfactual baseline</strong>. Instead of estimating V(sₜ) — how good is this state overall — POCA estimates for each agent i :</p><p><strong>Ψᵢ(sₜ, aᵢₜ) = Q(sₜ, aᵢₜ, a₋ᵢₜ) — b(sₜ, a₋ᵢₜ)</strong></p><p>Where :</p><ul><li>Q(sₜ, aᵢₜ, a₋ᵢₜ) = value of agent i taking action aᵢₜ while all other agents take actions a₋ᵢₜ</li><li>b(sₜ, a₋ᵢₜ) = <strong>baseline</strong> — the expected value if agent i&#39;s contribution is removed</li></ul><p>The baseline b is computed by the centralized critic marginalizing over agent i’s actions :</p><p><strong>b(sₜ, a₋ᵢₜ) = E_{aᵢₜ ~ π_θᵢ} [ Q(sₜ, aᵢₜ, a₋ᵢₜ) ]</strong></p><p>In practice, this is approximated by the centralized critic with a <strong>self-attention mechanism</strong> over all agent observations. The critic attends over the set of agent observations {o₁, o₂, …, oₙ} to produce a value estimate that accounts for the full game state, not just one agent’s local view.</p><p>The resulting advantage for agent i is :</p><p><strong>Aᵢₜ = Ψᵢ(sₜ, aᵢₜ) = Q(sₜ, aᵢₜ, a₋ᵢₜ) — b(sₜ, a₋ᵢₜ)</strong></p><p>This is the <strong>counterfactual advantage</strong> — it measures how much better agent i’s action was compared to what would have happened if agent i had acted randomly (according to its current policy) while everything else stayed the same. This cleanly isolates each agent’s individual contribution to the outcome.</p><p>The <strong>“Posthumous”</strong> in the name refers to POCA’s handling of agents that die or leave the game mid-episode. In the original multi-agent setting, when an agent is eliminated, its observations stop but its earlier actions still contributed to the team’s eventual outcome. POCA handles this with a <strong>posthumous return</strong> — dead agents continue to receive credit updates for as long as their teammates are still alive, based on the centralized critic’s estimate of their contribution. In a 1v1 setting, this means the losing agent’s early-game actions still receive proper credit signal rather than being orphaned.</p><p>The full POCA loss for agent i is :</p><p><strong>L_POCA(θᵢ) = E [ min( rᵢₜ(θᵢ) · Aᵢₜ , clip(rᵢₜ(θᵢ), 1-ε, 1+ε) · Aᵢₜ ) ] — β · H[πᵢ]</strong></p><p>Which is structurally identical to the PPO objective, but with the counterfactual advantage Aᵢₜ replacing the standard PPO advantage. The centralized critic is trained with a separate value loss :</p><p><strong>L_VALUE = E [ (Vφ(sₜ, {oₖ}) — Rₜ)² ]</strong></p><p>Where Vφ is the centralized critic parameterized by φ, and Rₜ is the discounted return.</p><h4>Part 4 : Neural Network Architecture</h4><p>The policy is implemented as a two-headed Actor-Critic network :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WtVqBET6Z5xJUZdotuLsqg.png" /><figcaption>Structure of Neural Network Architecture</figcaption></figure><p><strong>Actor Head</strong> outputs the action distribution. The DodgeBall action space is mixed :</p><ul><li><strong>Continuous actions :</strong> movement (forward/back, left/right), camera rotation — output as mean μ and log std σ of a Gaussian distribution</li><li><strong>Discrete actions :</strong> throw ball, dash — output as categorical logits</li></ul><p>The actor samples from these distributions during training (exploration) and takes the argmax/mean during inference (exploitation).</p><p><strong>Critic Head</strong> outputs a single scalar V(s) — the estimated cumulative discounted reward from the current state. In POCA, a <em>second</em> centralized critic also receives the concatenated observations of all agents via self-attention. This centralized critic is only used during training to compute the counterfactual baseline; it is not part of the exported ONNX model.</p><p><strong>Why 512 × 3 instead of the default 256 × 2?</strong></p><p>The observation vector has 23 inputs, which is low-dimensional. But the <em>task</em> is high-complexity — the agent must simultaneously :</p><ul><li>Track opponent’s relative position and predict their trajectory</li><li>Manage throw cooldown and ball count</li><li>Decide between aggressive (throw) and defensive (dodge) modes</li><li>Plan positioning over a 1,000-step time horizon</li></ul><p>A 256×2 network was tested first and produced visibly lower ELO plateau at ~1,450. Switching to 512×3 allowed the policy to represent more complex nonlinear relationships between observations and actions, which is reflected in the higher final ELO of ~1,600. The additional parameters (~660k vs ~165k) are negligible in terms of inference cost but meaningfully increase representational capacity during training.</p><h3>Hyperparameter Configuration</h3><pre>behaviors:<br>  DodgeBall:<br>    trainer_type: poca<br>    hyperparameters:<br>      batch_size: 2048<br>      buffer_size: 20480<br>      learning_rate: 0.0003<br>      beta: 0.005<br>      epsilon: 0.2<br>      lambd: 0.95<br>      num_epoch: 3<br>      learning_rate_schedule: constant<br>    network_settings:<br>      normalize: false<br>      hidden_units: 512<br>      num_layers: 3<br>      vis_encode_type: simple<br>      goal_conditioning_type: none<br>    reward_signals:<br>      extrinsic:<br>        gamma: 0.999<br>        strength: 1.0<br>    keep_checkpoints: 40<br>    checkpoint_interval: 2000000<br>    max_steps: 50000000<br>    time_horizon: 1000<br>    summary_freq: 50000<br>    threaded: false<br>    self_play:<br>      save_steps: 500000<br>      team_change: 1000000<br>      swap_steps: 200000<br>      window: 10<br>      play_against_latest_model_ratio: 0.5<br>      initial_elo: 1200.0</pre><p>Let me walk through the non-obvious choices :</p><p><strong>batch_size: 2048 / </strong><strong>buffer_size: 20480</strong> — buffer is exactly 10× batch size, the standard POCA ratio. The larger batch size (2048 vs the common default of 1024) provides more stable gradient estimates per update, which matters when the opponent is constantly changing and the reward signal is noisy.</p><p><strong>gamma: 0.999</strong> — this is notably higher than the typical 0.99 default. A gamma this close to 1.0 means the agent discounts future rewards almost not at all — it cares nearly equally about a reward 100 timesteps away as one right now. This is intentional for dodgeball : the win reward only arrives at the <em>end</em> of a round that can last up to 5,000 steps. With gamma = 0.99, the win reward is discounted by 0.99^5000 ≈ 0 and becomes nearly invisible to the optimizer. With gamma = 0.999, it stays significant, keeping the agent focused on actually winning rather than just accumulating hit rewards.</p><p><strong>time_horizon: 1000</strong> — each trajectory segment collected before updating is 1,000 steps long. Combined with the long gamma, this ensures the agent sees enough of a round in each update window to understand the long-term consequences of its early-round positioning decisions.</p><p><strong>learning_rate_schedule: constant</strong> — unlike a linear decay schedule, the learning rate stays fixed at 0.0003 for the entire 50M-step run. This was chosen because self-play creates a continuously non-stationary problem — the opponent is always getting harder — so the agent needs to keep learning aggressively throughout training rather than slowing down in later stages.</p><p><strong>save_steps: 500000</strong> — a snapshot is saved every 500,000 steps (compared to the common 50,000). This means the opponent pool contains agents spread further apart in skill level, which creates more diverse training matchups and helps prevent the agent from over-specializing against a narrow range of opponent styles.</p><p><strong>window: 10</strong> — only the last 10 snapshots are kept as potential opponents. With save_steps: 500000, this means the opponent pool covers the last 5 million steps of training history — always staying competitive while not dragging in opponents from the very beginning who are too weak to provide useful signal.</p><p><strong>keep_checkpoints: 40 / </strong><strong>checkpoint_interval: 2000000</strong> — saves a full checkpoint every 2M steps, keeping up to 40 total. This gives a dense set of deployable ONNX models covering the full skill range from beginner to expert, which is exactly what the tiered difficulty system needs.</p><p><strong>play_against_latest_model_ratio: 0.5</strong> — 50% of games against the most recent agent version, 50% against historical snapshots from the window. Playing only against the latest version can cause &quot;cycling&quot; — the agent specializes to beat the current opponent then loses earlier skills when the opponent updates. The 50/50 split prevents catastrophic forgetting.</p><h3>Self-Play : The Engine of Emergent Skill</h3><p>Self-Play is what elevates this from “a trained AI” to “an AI that discovers strategies.” It deserves its own section.</p><p>The mechanism is simple : the agent trains by playing against <strong>saved snapshots of itself from earlier in training</strong>. Every <strong>500,000 steps</strong>, the current policy is saved as a checkpoint. Future training uses a pool of up to 10 of these checkpoints (window: 10) — some recent, some older — as opponents.</p><p>What emerges from this process is remarkable. In the early stages (0–500k steps), both copies of the agent move randomly, throw balls randomly, and miss most of the time. The reward signal is weak because nothing meaningful is happening.</p><p>Around 500k–1M steps, one of the agents stumbles onto the strategy of walking toward the opponent and throwing. This earns +0.1. The policy reinforces this behavior. The other agent — now training against this updated version — experiences getting hit and faces −1.0 loss penalties. It starts learning to step back.</p><p>This creates a feedback loop : one agent improves its attack, the other improves its defense. The attack improvement creates a harder opponent that forces further defense improvement. The defense improvement creates a more elusive opponent that forces better aiming. No human programmer authored this arms race — it bootstrapped from random behavior through competitive pressure.</p><p>By 5M+ steps, agents have independently discovered behaviors like :</p><ul><li>Throwing while strafing (harder to be hit, harder to predict throw trajectory)</li><li>Retreating after throwing to reset the engagement</li><li>Baiting the opponent into wasting their ball before attacking</li></ul><p>None of this was programmed. It emerged.</p><h4>Validation with ELO</h4><p>ELO tracking provides continuous validation. Every <strong>500,000 steps</strong> (save_steps: 500000), a snapshot of the current policy is saved and the agent&#39;s ELO updates based on match outcomes against its snapshot pool. A monotonically increasing ELO curve confirms genuine skill development. A plateauing ELO signals that training has stalled — usually due to reward imbalance or hyperparameter issues.</p><p>If ELO starts <em>decreasing</em>, that’s a red flag indicating policy collapse — the agent is catastrophically forgetting previously learned skills. In that scenario, increasing play_against_latest_model_ratio to keep more recent opponents in the mix typically fixes it.</p><h3><strong>The Three-Stage Training Pipeline : Building an Adaptive Opponent</strong></h3><p>Standard self-play alone produces a strong AI — but a fixed-strength one that always plays at maximum intensity. That’s a problem : an AI that destroys every beginner in seconds produces frustration, not learning. A good coach calibrates their intensity to the student.</p><p>To solve this, a <strong>three-stage training pipeline</strong> was implemented, inspired by curriculum learning principles. Each stage builds on the previous one.</p><h3>Stage 1 : The Sandbox (0–2M steps)</h3><p><strong>Goal :</strong> Learn the physics of the game — how to pick up balls, throw, and eliminate stationary targets.</p><p><strong>Opponent :</strong> The Blue agent is set to Heuristic Only with no human input — it stands still as a stationary dummy.</p><p><strong>Process :</strong> The Purple AI trains against a non-moving target for 2 million steps. This is the equivalent of practicing free throws before playing a real game. By the end of Stage 1, the AI reliably picks up balls, walks toward the opponent, and throws with basic accuracy.</p><p><strong>Why this matters :</strong> Starting self-play immediately from random behavior is inefficient. Both agents flail randomly for millions of steps before either discovers that throwing is useful. Stage 1 bootstraps the basic skill of “throw at opponent” before the competitive pressure of self-play begins.</p><p><strong>Training command for Stage 1 :</strong></p><pre>py -3.10 -c &quot;from mlagents.trainers.learn import main; main()&quot; <br>    &quot;config/dodgeball_adaptive.yaml&quot; <br>    --run-id dodgeball_stage1 <br>    --time-scale 20</pre><p><em>Set Blue agent Behavior Type to </em><em>Heuristic Only before running.</em></p><h3>Stage 2 : The Crucible (2M–30M steps)</h3><p><strong>Goal :</strong> Develop Pro-level tactics through competitive self-play — dodging, aiming at moving targets, aggressive positioning.</p><p><strong>Opponent :</strong> Both Blue and Purple agents use the same policy, trained against each other.</p><p><strong>Process :</strong> This is the core self-play phase. Both agents are set to Default behavior type. Training initializes from the Stage 1 checkpoint so it starts with basic throwing skill already learned.</p><p><strong>Training command for Stage 2 :</strong></p><pre>py -3.10 -c &quot;from mlagents.trainers.learn import main; main()&quot; <br>    &quot;config/dodgeball_adaptive.yaml&quot; <br>    --run-id dodgeball_stage2 <br>    --initialize-from dodgeball_stage1 <br>    --time-scale 20</pre><p>ELO climbed to approximately 1,600 by the end of Stage 2 — meaningfully harder to beat than a beginner human player, with developed dodging and aiming behavior.</p><h3>Stage 3 : Curriculum Learning — Teaching the AI to Hold Back (10M steps)</h3><p><strong>Goal :</strong> Teach the Pro-level AI to recognize player skill and modulate its aggression accordingly.</p><p><strong>The core insight :</strong> A Pro-level AI that always plays at full strength is useless for training beginners. It destroys them in seconds, producing frustration rather than learning. A good coach calibrates their intensity to the student. This stage teaches the AI to do exactly that.</p><p><strong>How it works :</strong> At the start of every training episode, RandomizeOpponentSkillProfile() runs and assigns random values to the Blue agent&#39;s PlayerMetricsTracker:</p><pre>public void RandomizeOpponentSkillProfile()<br>{<br>    if (purpleAgentTracker == null) return;<br><br>    // Continuous random values — infinite skill levels between 0.0 and 1.0<br>    purpleAgentTracker.currentWinRate = Random.Range(0.0f, 1.0f);<br>    purpleAgentTracker.currentHitAccuracy = Random.Range(0.0f, 1.0f);<br>}</pre><p>This exposes the AI to the full continuous spectrum of skill levels during training — not just three fixed difficulty tiers. Over millions of episodes, the AI learns the mapping: low metrics → hold back, high metrics → go all out.</p><p>Why continuous random values rather than 3 fixed profiles? Fixed profiles (Newbie/Medium/Pro) produce an AI that recognizes three discrete states. Continuous random values produce an AI that understands a smooth spectrum — which is what real human skill variation looks like.</p><p><strong>Training command for Stage 3 :</strong></p><pre>py -3.10 -c &quot;from mlagents.trainers.learn import main; main()&quot; <br>    &quot;config/dodgeball_adaptive.yaml&quot; <br>    --run-id dodgeball_stage3 <br>    --initialize-from dodgeball_stage2 <br>    --time-scale 20</pre><p><strong>Note on ELO during Stage 3 :</strong> ELO drops to approximately 1,150–1,200 during Stage 3. This is expected and is actually proof the system is working — the AI is deliberately losing rounds against simulated “Newbie” opponents to learn restraint. A static ELO during Stage 3 would indicate the AI isn’t actually adapting.</p><h3>The PlayerMetricsTracker : Connecting Training to Runtime</h3><p>The adaptive difficulty system requires a bridge between training (simulated metrics) and runtime (real human metrics). This is the PlayerMetricsTracker component.</p><p>The rolling window of 10 games is critical. A naive implementation that averages across all games ever played would be too slow to respond — a player who has improved dramatically over 50 games would still show a mediocre skill rating because their early losses drag down the average. The rolling window ensures the AI responds to the player’s <strong>current</strong> skill, not their historical average.</p><pre>public class PlayerMetricsTracker : MonoBehaviour<br>{<br>    public float currentWinRate = 0.5f;<br>    public float currentHitAccuracy = 0.5f;<br><br>    private Queue&lt;bool&gt; recentWins = new Queue&lt;bool&gt;();<br>    private Queue&lt;bool&gt; recentHits = new Queue&lt;bool&gt;();<br>    private int windowSize = 10; // rolling window of last 10 games<br><br>    public void RegisterShot(bool wasHit)<br>    {<br>        recentHits.Enqueue(wasHit);<br>        if (recentHits.Count &gt; windowSize)<br>            recentHits.Dequeue();<br><br>        int hits = 0;<br>        foreach (bool h in recentHits)<br>            if (h) hits++;<br><br>        currentHitAccuracy = (float)hits / recentHits.Count;<br>    }<br><br>    public void RegisterGameResult(bool playerWon)<br>    {<br>        recentWins.Enqueue(playerWon);<br>        if (recentWins.Count &gt; windowSize)<br>            recentWins.Dequeue();<br><br>        int wins = 0;<br>        foreach (bool w in recentWins)<br>            if (w) wins++;<br><br>        currentWinRate = (float)wins / recentWins.Count;<br>    }<br>}</pre><p>After every game ends in DodgeBallGameController, the human metrics are synced to the Purple agent&#39;s tracker so the AI reads updated values next round :</p><pre>// EndGame() — called after every round<br>bool humanWon = winningTeam == 0;<br>humanPlayerMetrics.RegisterGameResult(humanWon);<br><br>// Sync to purple agent so AI reads updated metrics<br>purpleAgentTracker.currentWinRate = humanPlayerMetrics.currentWinRate;<br>purpleAgentTracker.currentHitAccuracy = humanPlayerMetrics.currentHitAccuracy;</pre><p>The syncing step is essential — the Purple AI reads its own purpleAgentTracker, so human metrics must be copied there after every game for the AI to see them.</p><p>The full adaptation loop looks like this :</p><blockquote>Human plays round → Hit registered → accuracy updates → Round ends → Win/loss registered → win rate updates → Metrics synced to Purple AI’s tracker → Next round starts → Purple AI reads updated winRate + accuracy → Neural network produces behavior matching that skill level → Human faces appropriately calibrated opponent</blockquote><h3>Verifying Adaptation : The SkillDisplay UI</h3><p>Because the adaptation is subtle — the AI doesn’t announce “I’m now playing at Medium difficulty” — a real-time display was added to make the skill tracking visible :</p><pre>public class SkillDisplay : MonoBehaviour<br>{<br>    public PlayerMetricsTracker playerMetrics;<br>    public TMP_Text displayText;<br><br>    void Update()<br>    {<br>        float winRate = playerMetrics.currentWinRate;<br>        float accuracy = playerMetrics.currentHitAccuracy;<br>        float skillScore = (winRate + accuracy) / 2f;<br><br>        string level = skillScore &lt; 0.33f ? &quot;NEWBIE&quot; :<br>                      skillScore &lt; 0.66f ? &quot;MEDIUM&quot; : &quot;PRO&quot;;<br><br>        displayText.text =<br>            $&quot;Win Rate: {winRate:F2}\n&quot; +<br>            $&quot;Accuracy: {accuracy:F2}\n&quot; +<br>            $&quot;AI sees you as: {level}&quot;;<br>    }<br>}</pre><p>This overlay serves two purposes : it lets the player see their current skill rating in real time, and it makes the adaptation mechanism transparent — you can watch the AI’s perception of your skill change as you win or lose rounds.</p><h3>Data Collection and the Non-Trivial Data Source</h3><p>This project uses no external dataset. There are no CSV files, no labeled examples, no downloaded archives. Every piece of training data is <strong>self-generated during training</strong> through the interaction of two agents with a physics simulation.</p><p>This is genuinely non-trivial in ways worth unpacking.</p><h4>The Data Generation Process</h4><p>The environment ensures these experiences are diverse through four mechanisms :</p><p><strong>Random spawn positions </strong>: Each episode, both agents spawn at random locations. No two episodes start the same way, preventing spawn-point-specific strategies.</p><p><strong>Random ball placement </strong>: Balls respawn at random positions after each throw, forcing the agent to learn ball retrieval as a general skill.</p><p><strong>Self-Play non-stationarity </strong>: The opponent is always getting better. Experience at step 5M is fundamentally different from experience at step 1M because the opponent is vastly more capable.</p><p><strong>Stage 3 skill randomization </strong>: Continuous random skill profile values in Stage 3 mean every training episode presents a different simulated opponent skill level, covering the entire (0.0, 1.0) × (0.0, 1.0) skill space.</p><p>This training data <strong>cannot be reproduced identically across runs</strong> — it depends on random seed, hardware timing (which affects physics simulation), and the emergent behavior of the agents. The Ryzen 9800X3D + RTX 4070 Ti Super training rig isn’t just a performance detail — it’s part of the data generation process itself.</p><h3>Training and Error Analysis : What Goes Wrong</h3><p>No RL training run goes perfectly. Here are the failure modes I encountered, how to diagnose them, and how to fix them.</p><h4>Problem : AI Only Throws Randomly in Early Training</h4><p><strong>Cause </strong>: Insufficient training steps. The agent hasn’t received enough reward signal to reinforce throwing behavior.</p><p><strong>Diagnosis </strong>: Reward curve flat near zero. Episode length close to maximum (5,000 steps) — rounds are timing out rather than ending through wins/losses.</p><p><strong>Fix </strong>: Continue training. This resolves itself between 200k–500k steps. If it persists past 1M steps, verify the hit reward (+0.1) is correctly wired in the reward function.</p><h4>Problem : AI Stops Improving After Early Progress</h4><p><strong>Cause </strong>: Learning rate too high for later training phases. The policy overshoots good solutions and oscillates.</p><p><strong>Diagnosis </strong>: ELO curve plateaus or oscillates. Reward per episode stops increasing despite continued training.</p><p><strong>Fix </strong>: Reduce learning rate from 3e-4 to 1e-4 and restart with --initialize-from to preserve learned skills. Since this config uses learning_rate_schedule: constant, switching to a decay schedule is not the fix — manually restarting with a lower fixed rate is.</p><h4>Problem: AI Only Dodges, Never Throws</h4><p><strong>Cause </strong>: The loss penalty (−1.0) dominates the reward signal relative to hit bonuses (+0.1). The agent discovers that avoiding combat entirely is the safest strategy.</p><p><strong>Diagnosis </strong>: Hit rate near zero. Agent constantly moves away from balls. Episode rewards clustered around 0 (ties rather than wins or losses).</p><p><strong>Fix </strong>: Increase the EliminationHitBonus reward, or add a mild time penalty to discourage passive play. Rebalance until aggressive play is clearly more valuable.</p><h4>Problem : Unstable Training — Reward Oscillates Wildly</h4><p><strong>Cause </strong>: Buffer size too small relative to episode length and batch size.</p><p><strong>Diagnosis </strong>: Large swings in episode reward between checkpoints. ELO fluctuates up and down rather than trending upward.</p><p><strong>Fix </strong>: Ensure buffer_size is at least 10× batch_size. This config already uses that ratio (20480 = 10 × 2048), which is why this failure mode didn&#39;t appear — worth knowing for anyone adapting these settings.</p><h4>Problem : ELO Crashes After Resume</h4><p><strong>Cause </strong>: window: 100 self-play pool causes agents to be matched against opponents from 50M+ steps ago after any interruption — opponents they have no chance against.</p><p><strong>Diagnosis </strong>: ELO drops sharply immediately after a --resume command.</p><p><strong>Fix </strong>: Use window: 10. This was discovered through three separate failed training runs before being identified as the root cause.</p><h3>Problem : Adaptive Difficulty Not Responding (Stage 3 Specific)</h3><p><strong>Cause </strong>: RandomizeOpponentSkillProfile() overwrites real metrics during gameplay because CurrentSceneType is set to Training instead of Game.</p><p><strong>Diagnosis </strong>: SkillDisplay shows the same skill level every round regardless of performance.</p><p><strong>Fix </strong>: Set CurrentSceneType to Game in the play scene Inspector. Add a training-only guard:</p><pre>if (CurrentSceneType == SceneType.Training)<br>{<br>    // Only randomize during training, not gameplay<br>    purpleAgentTracker.currentWinRate = Random.Range(0.0f, 1.0f);<br>    purpleAgentTracker.currentHitAccuracy = Random.Range(0.0f, 1.0f);<br>}</pre><h3>Deployment : From Training Run to Playable Game</h3><p>After training, Unity ML-Agents exports the trained policy as an <strong>ONNX file</strong> (Open Neural Network Exchange). ONNX is a cross-platform neural network format — the same file can run in Unity on any platform that supports the ML-Agents inference runtime (PC, Mac, Linux, and mobile).</p><p>The export path looks like :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*FzlkRCfrR9PjACVXxt0KNg.png" /><figcaption>example of the result update in the terminal</figcaption></figure><h4>Testing out in Unity : Step by Step</h4><ol><li>Select the Purple Agent in the scene hierarchy</li><li>Drag the Stage 3 .onnx file into the Unity project</li><li>Drag the .onnx file into Behavior Parameters → Model in the Inspector</li><li>Set <strong>Behavior Type</strong> to Inference Only</li><li>Set the Blue Agent’s <strong>Behavior Type</strong> to Heuristic Only</li><li>Set <strong>CurrentSceneType</strong> to Game</li><li>Create a PlayerMetrics GameObject with PlayerMetricsTracker component</li><li>Assign it to both humanPlayerMetrics and purpleAgentTracker on the game controller</li><li>Press Play</li></ol><p>The human player controls Blue with WASD movement, mouse aim, and spacebar throw. The Purple agent runs the trained ONNX model at inference, processing its observation vector through the neural network to produce actions in real time.</p><h4>The Adaptive Difficulty System in Action</h4><p>AI in game will have 3 stages brain handles difficulty entirely automatically :</p><p><strong>New player starts → AI defaults to medium (winRate : 0.5, accuracy : 0.5)</strong></p><p><strong>Player keeps losing → winRate drops → accuracy drops → AI reads lower skill → plays more restrained</strong></p><p><strong>Player improves →winRate rises → accuracy rises → AI reads higher skill → increases aggression</strong></p><p><strong>Player masters the AI → AI plays at full Pro-level intensity</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FCzEc5FI6ad8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DCzEc5FI6ad8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FCzEc5FI6ad8%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a46127e91d88ca0e9e0a93939c725ff0/href">https://medium.com/media/a46127e91d88ca0e9e0a93939c725ff0/href</a></iframe><h3>Final Results</h3><h4>Training Metrics Summary — Three Stages</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*Wzkx6AdGvQY5jaKudmaJgQ.png" /></figure><p>The Stage 3 ELO drop is expected and meaningful — the AI is deliberately holding back against simulated beginner opponents to learn restraint, not losing skill.</p><p><strong>Hit rate progression:</strong></p><ul><li>Untrained agent: ~5% (random)</li><li>End of Stage 1: ~15–20% (aiming at stationary targets)</li><li>End of Stage 2: ~40–50% (predictive aiming at moving targets)</li></ul><h4>Full Comparison with Baselines</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*YieW0pWW4pdXKqvXV7OTlw.png" /></figure><p>The critical advantage over scripted systems isn’t raw hit rate — it’s <strong>the source of the behavior</strong>. RL-discovered strategies are genuinely responsive to the opponent. The AI learns to aim where the opponent is <em>going</em>, not just where they are. And with Stage 3, it learns to calibrate <em>how hard</em> it plays based on who it’s facing.</p><p>No programmer told it this. It discovered it because doing so wins more rounds.</p><h3>What I Learned and What’s Next</h3><h4>Lessons from the Build</h4><p><strong>Reward design is everything.</strong> Every hour spent thinking carefully about the reward function saved five hours of debugging degenerate behavior.</p><p><strong>Self-play stability requires careful configuration.</strong> The play_against_latest_model_ratio parameter is not cosmetic. The window size critically affects resume stability — window: 10 is the stable choice for projects that need to pause and resume training.</p><p><strong>The environment is a hyperparameter.</strong> Arena scale, ball count, HP values, and stun duration all dramatically affect training dynamics.</p><p><strong>Curriculum learning compounds with self-play.</strong> The three-stage pipeline produced noticeably better final behavior than pure self-play alone — Stage 1 bootstrapped basic skills efficiently, Stage 2 developed them into Pro-level tactics, and Stage 3 added the adaptive layer that makes this actually useful for training humans.</p><p><strong>Adaptation requires careful metric plumbing.</strong> The most common failure mode in the adaptive system was metric updates getting lost between components. The RegisterShot() / RegisterGameResult() calls need explicit wiring — they don&#39;t happen automatically.</p><h4>Future Directions</h4><p><strong>Imitation Learning bootstrap :</strong> Record footage of expert human players and use behavioral cloning to warm-start the policy from human-like strategies before beginning RL training.</p><p><strong>Observation space expansion :</strong> Add opponent velocity to the observation vector. This would allow predictive throwing — leading targets instead of aiming at current position.</p><p><strong>3D FPS variant :</strong> The current environment is a top-down 2D arena. Expanding to full 3D with a first-person camera would make the aim training more directly applicable to FPS games.</p><p><strong>Deeper adaptive curriculum :</strong> Instead of a single scalar skill score, track multiple independent skill dimensions (accuracy, dodging, aggression) and let the AI adapt each axis independently.</p><h3>Conclusion</h3><p>The core argument of this project is simple: the bottleneck in aim training is not how many repetitions you do — it’s the quality of the opponent you’re practicing against. Scripted bots produce scripted skills that don’t transfer. An opponent that learns teaches you to learn.</p><p>Reinforcement Learning with Self-Play produces exactly the kind of opponent that was missing from existing aim trainers: one that discovers real strategies, responds to your tendencies, and scales continuously in difficulty as your skill improves. Not because a programmer tuned it to match you — but because millions of competitive interactions forced it to develop.</p><p>The three-stage training pipeline extended this further: Stage 1 bootstrapped basic skills, Stage 2 developed Pro-level tactics through competitive pressure, and Stage 3 taught the AI to recognize and respond to the human player’s current skill level — automatically calibrating its intensity so the match is always challenging but never hopeless.</p><p>This project reached ELO ~1,600 at 25 million training steps using POCA + self-play on a 1v1 modified DodgeBall environment. The adaptive difficulty system responds to win rate and accuracy in real time, producing an opponent that genuinely scales with you as you improve.</p><p>Those are questions worth asking, and building this project gave me much better answers to them than I expected.</p><p><em>If you have questions about the reward design, POCA vs PPO tradeoffs, or training stability, leave a comment — I’ll do my best to respond to every comment.</em></p><p><em>And if there are any errors in this article, please let me know. I am new to writing, and this is my very first article!</em></p><p><em>Thanks for reading ;)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=921951fdc923" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>