<?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[initialPrefabs - Medium]]></title>
        <description><![CDATA[An indie game studio in NYC - Medium]]></description>
        <link>https://medium.com/initialprefabs?source=rss----799332f533ba---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>initialPrefabs - Medium</title>
            <link>https://medium.com/initialprefabs?source=rss----799332f533ba---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 16 May 2026 04:00:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/initialprefabs" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[Physics Collision and Spatial Mapping]]></title>
            <link>https://medium.com/initialprefabs/physics-collision-and-spatial-mapping-5397610c9d63?source=rss----799332f533ba---4</link>
            <guid isPermaLink="false">https://medium.com/p/5397610c9d63</guid>
            <category><![CDATA[physics-engine]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[unity]]></category>
            <dc:creator><![CDATA[Porrith Suong]]></dc:creator>
            <pubDate>Thu, 13 Aug 2020 18:45:31 GMT</pubDate>
            <atom:updated>2020-08-14T11:57:03.465Z</atom:updated>
            <content:encoded><![CDATA[<p>Physics engines are wildly known and solved spaces as there are plenty of tutorials and frameworks out there to help you write your own version too. To name a few tutorials:</p><ul><li><a href="https://www.sciencedirect.com/book/9780123694713/game-physics-engine-development">Game Engine Physics Development</a> by <a href="https://github.com/idmillington/cyclone-physics/">Ian Millington</a></li><li><a href="https://gamedevelopment.tutsplus.com/series/how-to-create-a-custom-physics-engine--gamedev-12715">How to Create a Custom Physics Engine</a> by Randy Gaul</li></ul><p>And some frameworks:</p><ul><li><a href="https://github.com/erincatto/box2d">Box2D</a></li><li><a href="https://github.com/projectchrono/chrono">Project Chrono</a></li></ul><p>But something that has typically interested me with physics engine is how to potentially detect collisions. Now this is primarily a data structure problem, as we would have to reason about how we would want to structure all of our physics bodies based on their positions. Ultimately, the end goal of this structure is to provide a fast way to check potential collisions without having to brute force and compare every single physics body with each other (this becomes an n² check!).</p><h3>Spatial Hashmaps</h3><p>One way to store physics bodies is to divide your play area into a group of cells as a grid. We can then store a bunch of physics bodies into a cell and determine which cells that each physics body is in. By design spatial hash maps are hash maps with chained linked lists as their values. Therefore, potential physics bodies in the same cell will be registered into the same hash.</p><pre>Key Values<br>---------<br>1 -&gt; [A] [B]<br>2 -&gt; [D]<br>3 -&gt; [E] [F] [Z]</pre><pre>An example with the left column being the key and the right column being multiple values with the same key.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*BUBJsoQ3qHvwRpJUlyapSA.png" /><figcaption>By design we want our green dots to potentially be registered into the same red cell</figcaption></figure><h4>The Hash Function</h4><p>Each physics body is typically defined with a position represented as Cartesian coordinates (float3) . Ultimately, the hash function will take each axis value and combine the values into a key which we would use to register into the hash map.</p><p>A good hash function balances balances the number of potential collision we have per cell. If we have a very accurate hash function, then we may generate new hash map entries for physics bodies which are close together. If we have an inaccurate hash function, then we potentially may add in all physics body positions into a few cells, which may lead us closer to polynomial time to detect collisions.</p><p>By dividing the physics body position x and y values by the grid size and adding the components together, we get a decent hash that can contain multiple physics bodies. Here’s the pseudo code of the description above.</p><pre>int Key(int size, float3 v)<br>{<br>  return ((int)(floor(v.x / size) + floor(v.y / size)) * size);<br>}</pre><pre>Examples for: (1, 1, 0), (2, 1, 0), and (20, 11, 0) this hash function will produce:</pre><pre>Point: (1, 1, 0)<br>-------<br>(floor(1 / 10) + floor(1 / 10)) * 10 = hash_value<br>(0 + 0) * 10 = hash_value<br>0 = hash_value</pre><pre>Point: (2, 1, 0)<br>-------<br>(floor(2 / 10) + floor (1 / 10)) * 10 = hash_value<br>(0 + 0) * 10 = hash_value<br>0 = hash_value</pre><pre>Point: (20, 11, 0)<br>-------<br>(floor(20 / 10) + floor (11 / 10)) * 10 = hash_value<br>(2 + 1) * 10 = hash_value<br>30 = hash_value</pre><h3>Physics Shapes</h3><p>Physics bodies are typically defined with a physics shape. For my needs in Carté Diem, most physics bodies currently are defined as a box. Complex shapes will eventually be included later down the line. For example, our player Ellen can occupy multiple cells:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/209/1*MQtJwYrEckp9LTPSVdfLOw.png" /><figcaption>Ellen occupying multiple cells of size 10.</figcaption></figure><p>Now the simplest way to ensure that Ellen occupies multiple cells is likely to brute force and sample some points along each edge of the box. This is obviously not a very nice solution because we can potentially register the same physics body multiple times to the same hash. We can, of course, do a final check to ensure we uniquely add physics bodies to a hash, but we possibly would not know how many times we have to perform this uniqueness check.</p><p>But even with brute force, a question like this popped up during development:</p><ul><li>Can we accurately get all the cells that the box physics shape occupy?</li></ul><p>Well this problem was similar to an old Graphics problem I learned about which was determining which pixel a line potentially occupied. This is known as <a href="https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm">Bresenham’s Line Algorithm</a>.</p><p>The idea behind the algorithm is to calculate the slope of a line segment and to sample intervals to check which cell the sampled line segment belongs to. Here’s the pseudocode implemented in my physics engine below.</p><pre>Line(float2 from, float2 to, int cellSize) <br>{<br>  value = floor(from);<br>  diff = to - from;<br>  step = sign(diff);<br>  offset = float2(<br>   to.x &gt; from.x ? <br>     ceil(from.x) - from.x : <br>     from.x - floor(from.x),<br>   to.y &gt; from.y ? <br>     ceil(from.y) - from.y : <br>     from.y - floor(from.y));<br>  angle = atan2(-diff.y, diff.x);<br>  angles = float2(cos(angle), sin(angle));<br>  tMax   = offset / angles;<br>  tDelta = cellSize / angles;<br>  dist = abs(floor(to.x) - floor(from.x)) + <br>    abs(floor(to.y) - floor(from.y));</pre><pre>  // v will be associated cell&#39;s position. We can add<br>  // this to a collection or process this immediately<br>  v = FloorToNth(value, cellSize);<br>  <br>  for (int i = cellSize; i &lt; dist; i+=cellSize) <br>  {<br>    if (abs(tMax.x) &lt; abs(tMax.y)) <br>    {<br>       tMax.x += tDelta.x;<br>       value.x += step.x * cellSize;<br>    }<br>    else <br>    {<br>       tMax.y += tDelta.y;<br>       value.y += step.y * cellSize;<br>    }<br>    // Recalcule v again to find a new cell<br>    v = FloorToNth(value, cellSize);<br>  }<br>}</pre><p>What makes Brehansem’s line algorithm incredibly useful is visualization. If we collect all cells associated with the line we can provide the cell’s position and draw a heat map which will visualize the density of potential colliders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*N2DF805FoVWK-pyTNR8PMg.gif" /><figcaption>Visualizing potential collisions using Brehansem’s Line Algorithm and drawing voxels to see potential collisions per cell. It’s worth noting that this is built in Unity 2020.1.x using an Entity Component System workflow.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5397610c9d63" width="1" height="1" alt=""><hr><p><a href="https://medium.com/initialprefabs/physics-collision-and-spatial-mapping-5397610c9d63">Physics Collision and Spatial Mapping</a> was originally published in <a href="https://medium.com/initialprefabs">initialPrefabs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Going About Testing in Unity ECS]]></title>
            <link>https://medium.com/initialprefabs/going-about-testing-in-unity-ecs-53887477c163?source=rss----799332f533ba---4</link>
            <guid isPermaLink="false">https://medium.com/p/53887477c163</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[test-driven-development]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Porrith Suong]]></dc:creator>
            <pubDate>Tue, 26 Feb 2019 19:37:52 GMT</pubDate>
            <atom:updated>2019-04-01T17:01:26.582Z</atom:updated>
            <content:encoded><![CDATA[<p>With the Conversion workflow which has been recommended by Unity the method I suggested of instantiating a prefab will <strong><em>likely </em></strong>be deprecated. Archived items will still be available for reference’s sake.</p><p>Questions or comments I hear quite often when I mention I write unit tests for games are:</p><blockquote>Why do you need to write tests when games are visual and change over time?</blockquote><blockquote>Can’t you just ask someone to help you test your game so you can catch bugs?</blockquote><p>Those questions are quite true to a degree and there are certainly times when I think about not writing tests and just being able to move on to the next feature instead. But, more often than not, some of the pain points I had with scaling a game are:</p><ul><li>it’s easy to spot bugs with your eyes but it’s difficult to pin point/debug where the issue is</li><li>with a small team and when we’re under crunch time, not everyone has the time to regressively play test features to ensure they work</li></ul><p>You won’t completely solve those issues with unit testing but you can certainly alleviate the pain of those common scenarios by writing <strong><em>smart</em></strong> unit tests.</p><h3>Game Background</h3><p>So before I get into how my team and I go about unit testing, it’s worth explaining what our game, Project Arena (name pending), is basically about.</p><p>Project Arena is a 2D arena local multiplayer game where players choose cards between each round to defeat their opponent in battle. The game is played with a common local server, like your laptop, and smart phones as client controllers and secondary screens for each player.</p><p>I’ll certainly post more about this during the upcoming weeks/months.</p><p>Because we’re dealing with network code, we actually have to write tests to reason about our logic to ensure that we expect things to happen correctly despite the network connection. But in this blog, I’ll actually walk you through one of our test which tests our character’s visual effect and gameplay mechanic.</p><p><strong>Note</strong>: From here on out, I’ll refer to visual effect as VFX.</p><p>We build our game using <strong>Hybrid Entity Component System</strong> (ECS), which is an architecture that allows us to separate data away from logic providing us ease of scale and performance benefits.</p><p>For a brief overview<strong>, Arturo Nereu</strong> of Unity has a nice comic strip which explains ECS in a digestible manner.</p><p><a href="https://github.com/ArturoNereu/ECS_101/blob/master/ECS_Infographic/ECS_Infographic_EN.jpg">ArturoNereu/ECS_101</a></p><p>So much thanks and credits to him!</p><h3>The Game Mechanic</h3><p>The playable character is very similar to the mechanics of Megaman/X/Zero. The player can move, jump, shoot projectiles and use cards. Unlike Megaman, our player actually charges automatically since holding down a button on a phone is very uncomfortable while moving and performing other simultaneous actions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*wn6sJsuaf5OBm6guWghnyQ.gif" /><figcaption>Our stand-in character from the 2DGameKit, Ellen automatically charging!</figcaption></figure><h3>Understanding the Data Behind Charging a Shot</h3><p>Even though we use the Entity Component System, we still have dependencies on MonoBehaviour such as the Particle System.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*iNMB31r5NAZXAD0rCAVXhg.png" /><figcaption>Structurally, our Particle Systems are set up with the large circle in the center as the parent ChargeEffect Particle System, while the smaller circles moving towards the center is child SubCharge Particle System.</figcaption></figure><p>In our case, we treat MonoBehaviours as simply objects with properties, with limited functionalities. Below is a table which shows the minimum amount of data we need to get the effect shown in the gif:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*LdrKQLaVGLI1UtjUvYrHFg.png" /></figure><h3>Implementing the Charge Shot Logic</h3><p>So the Charge Shot behaviour is pretty simply, when the ChargeShotTimer’s Current time is <strong><em>greater than or equal </em></strong>to the max Wait time, the larger particle in the center (the parent) will play, otherwise it disappears. The child particle will always play when the Current time is greater than epsilon.</p><blockquote>Epsilon denotes the smallest value, in our case we treat epsilon as effectively 0.</blockquote><p>When shooting, the Current time is effectively 0, thus both particle systems will <strong><em>stop</em></strong> playing<strong><em>.</em></strong> This ensures that <strong><em>visually</em></strong>, our player does not look like they are getting a more powerful shot when shooting.</p><p>Below is the logic for our ChargeFXIndicatorSystem, which handles what was stated above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93e5057951308d626d79db2a1141e1e0/href">https://medium.com/media/93e5057951308d626d79db2a1141e1e0/href</a></iframe><p>Since we don’t actually set up our VFX to be a child of Ellen, we internally map each Particle System by its player’s ID. This keeps our character prefab light with only the data we need and keeps our VFX as a separate entity.</p><h3>But, what tests are we actually writing for the VFX?</h3><p>The tests are quite simple with function names that are quite verbose:</p><ul><li>ChargingAttackShowsChildIndicator — if we charge a shot, we show our VFX’s child Particle System</li><li>FullyChargedAttackShowsBothIndicators — when we fully charge a shot, we show our VFX’s parent and child Particle System</li><li>ReleasedChargedAttackShowsNoIndicator — when we shoot, we show neither the parent VFX or child VFX</li></ul><h3>[ARCHIVED] Prepping Up Our Tests</h3><p>One of the benefits of testing in Unity is that we can test with real prefabs we use in our game.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*9VOfAeE77TULWpZCv6PKTQ.png" /><figcaption>Above is our player entity with the ChargeShotTimer boxed in light blue. Similarly, our ParticleSystemPair and ID proxies are highlighted in our VFX entity.</figcaption></figure><p>To use these assets in our tests, we built a utility function to grab a copy of the assets from the project. This is the code version of dragging a prefab into the scene!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99a4f6ad652a472a407ba88bb07d7b00/href">https://medium.com/media/99a4f6ad652a472a407ba88bb07d7b00/href</a></iframe><h4>Test Fixture Set Up</h4><p>Now that we have the assets, we need to set up a clean environment to perform our tests. To do this, we create a text fixture, which has the bare minimum implementation of setting up and tearing down a clean environment for each test to run in.</p><p>This helps isolate our logic from the rest of the game/systems so we ensure that the logic works correctly on its own. Below is our minimal implementation of our test fixture.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c3f439c64b762aa935b0f76f724fdca/href">https://medium.com/media/2c3f439c64b762aa935b0f76f724fdca/href</a></iframe><p>All we do in our SetUp function is we create a new test world and cache the previous, one so we can restore it in our Teardown function after a test finishes.</p><p>To quickly recap we want to test the following scenarios:</p><ul><li>if we charge a shot, we show our VFX’s child Particle System</li><li>when we fully charge a shot, we show our VFX’s parent and child Particle System</li><li>when we shoot, we show neither the parent VFX or child VFX</li></ul><p>Here’s our ChargeFXIndicatorSystemTests:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/187dee6a140ea770573d6fedc3fd7153/href">https://medium.com/media/187dee6a140ea770573d6fedc3fd7153/href</a></iframe><p>For each test we just have to set our ChargeShotTimer and ensure that the <strong>Current</strong> time is either greater than, equal to, or less than our <strong>Wait </strong>time.</p><ul><li>ChargingAttackShowsChildIndicator — we can reason that the Current time has to be larger than 0 but less than our Wait time, so we just set the Current time to be 1 second.</li><li>We only expect there to be 1 entity available after the ChargeFXIndicatorSystem updates, otherwise our system is doing something odd and creating more entities than we need!</li><li>As for our VFX, we should expect that only the child VFX plays and not the parent, otherwise our system’s logic does not operate on our data correctly.</li></ul><p>The rests of the tests follow the same structure but just test other values of the Current time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*7YXzvxn3MUw9T8ENh_k2Tw.gif" /><figcaption>After running all the tests you can enjoy the satisfying feeling of all the green check marks flying through the Unity Test Runner.</figcaption></figure><h3>Some Closing Notes</h3><p>So that is the general gist of how my team and I go about testing. We usually plan our systems and tend to ask questions regarding the game design and the data we need first. This enables to really understand our direction before we start writing any code.</p><p>We also don’t go about<strong><em> writing tests for every single case possible</em></strong>. We’re a small team, so we write tests for our primary essential features. This helps us iterate quickly on our infrastructure and be able to call out poor infrastructure choices we’ve made while we’re developing our game.</p><p>Unit testing certainly takes time and patience to do and by no means replaces manual QA testing. You’ll certainly need design feedback on your game, which unit tests can’t provide.</p><p>Some additional resources I read about unit testing that I found useful are:</p><ul><li><a href="https://blogs.unity3d.com/2018/11/02/testing-test-driven-development-with-the-unity-test-runner/">https://blogs.unity3d.com/2018/11/02/testing-test-driven-development-with-the-unity-test-runner/</a></li><li><a href="https://github.com/sophiaaar/tdd-pong">https://github.com/sophiaaar/tdd-pong</a></li><li><a href="https://docs.unity3d.com/Manual/testing-editortestsrunner.html">https://docs.unity3d.com/Manual/testing-editortestsrunner.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53887477c163" width="1" height="1" alt=""><hr><p><a href="https://medium.com/initialprefabs/going-about-testing-in-unity-ecs-53887477c163">Going About Testing in Unity ECS</a> was originally published in <a href="https://medium.com/initialprefabs">initialPrefabs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>