<?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 Federico Grenoville on Medium]]></title>
        <description><![CDATA[Stories by Federico Grenoville on Medium]]></description>
        <link>https://medium.com/@federicogrenoville?source=rss-fe9a23aaa782------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KeCfSkv1YVn8enpeI3mo9g.png</url>
            <title>Stories by Federico Grenoville on Medium</title>
            <link>https://medium.com/@federicogrenoville?source=rss-fe9a23aaa782------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 18:01:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@federicogrenoville/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[From one car to a fleet: asynchronous physics in UE5 that scales with multithreading]]></title>
            <link>https://levelup.gitconnected.com/from-one-car-to-a-fleet-asynchronous-physics-in-ue5-that-scales-with-multithreading-d322b2b94001?source=rss-fe9a23aaa782------2</link>
            <guid isPermaLink="false">https://medium.com/p/d322b2b94001</guid>
            <category><![CDATA[parallel-programming]]></category>
            <category><![CDATA[unreal-engine-5]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[vehicle-physics]]></category>
            <category><![CDATA[multithreading]]></category>
            <dc:creator><![CDATA[Federico Grenoville]]></dc:creator>
            <pubDate>Fri, 24 Oct 2025 11:10:37 GMT</pubDate>
            <atom:updated>2025-10-24T11:10:37.521Z</atom:updated>
            <content:encoded><![CDATA[<p>In video games — and real-time simulations in general — one of the top priorities is achieving stability and performance at runtime.</p><p>In the <a href="https://medium.com/gitconnected/taming-chaos-stable-vehicle-suspensions-with-async-physics-in-ue5-566369c7b097">previous article</a> I showed how to use <em>Chaos’</em> asynchronous physics to decouple the simulation from the frame rate and keep the delta time within safe bounds, avoiding the classic <a href="https://medium.com/gitconnected/tick-by-tick-how-unreal-engine-simulates-real-world-physics-4ac7bc9ee5fb">glitches caused by unstable integrators</a>. We nailed stability. But how do we get performance — what happens when the number of vehicles grows?</p><p>I restructured <a href="https://github.com/fgrenoville/Async-Physics-Suspension">the previous project</a> to simulate multiple vehicles in parallel, with a strict separation between simulation data (Physics Thread) and the Game Thread. Each vehicle has its own input/output buffers and an <strong>internal state</strong> managed exclusively on the Physics Thread.</p><p>All physics functionality now lives in a dedicated plugin: <strong><em>SmokinWheelsPhx</em></strong>.</p><p><strong>Scope note.</strong> This article won’t re-explain how the suspension is simulated or the core ideas behind Chaos physics — those are covered in the <a href="https://levelup.gitconnected.com/taming-chaos-stable-vehicle-suspensions-with-async-physics-in-ue5-566369c7b097">previous article</a>. If you’re new to those topics, I recommend reading that first. And if you want to try everything you see here, the <strong>GitHub link at the end </strong>points to this exact project (the one presented in this article), ready to build and test.</p><h4><strong>Plugin architecture overview</strong></h4><p>The goal of the plugin is to <strong>centralize</strong> asynchronous vehicle physics for <strong>each</strong> <em>Unreal </em>(<em>Chaos</em>) physics scene, without scattering callbacks and state across the project.<br> In <em>Unreal</em>, every UWorld has its own FPhysScene, and in some scenarios multiple scenes can coexist. A global <a href="https://en.wikipedia.org/wiki/Singleton_pattern">singleton</a> isn’t viable — you need <strong>one manager per physics scene</strong>.</p><p>To support that, I keep the following map:</p><pre>TMap&lt;FPhysScene*, FSWPAsyncPhysicsManager*&gt; SceneToPhysicsManagerMap;</pre><p>I use it to:</p><ul><li><strong>Instantiate exactly one manager per scene</strong> when <em>Chaos </em>initializes the FPhysScene .</li><li><strong>Quickly look up the right manager</strong> from any code that knows the scene (e.g., a component or a pawn): given an FPhysScene* I find the manager and operate on it.</li><li><strong>Isolate per-scene data</strong>: each manager owns its I/O buffers and per-vehicle state and registers the <em>Chaos</em> callbacks — no cross-talk between different scenes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zjew74yJzoTV7IMyRSy5ww.png" /></figure><h4>Plugin lifecycle</h4><p>At plugin startup I register the two physics-scene creation/destruction callbacks: OnPhysSceneInit and OnPhysSceneTerm.</p><pre>void FSmokinWheelsPhxModule::StartupModule()<br>{<br> // This code will execute after your module is loaded into memory; the exact timing is specified in the .uplugin file per-module<br> OnPhysSceneInitHandle = FPhysicsDelegates::OnPhysSceneInit.AddRaw(this, &amp;FSmokinWheelsPhxModule::PhysSceneInit);<br> OnPhysSceneTermHandle = FPhysicsDelegates::OnPhysSceneTerm.AddRaw(this, &amp;FSmokinWheelsPhxModule::PhysSceneTerm);<br>}<br><br>void FSmokinWheelsPhxModule::PhysSceneInit(FPhysScene* Scene)<br>{<br> new FSWPAsyncPhysicsManager(Scene);<br>}<br><br>void FSmokinWheelsPhxModule::PhysSceneTerm(FPhysScene* Scene)<br>{<br> FSWPAsyncPhysicsManager* PhysManager = FSWPAsyncPhysicsManager::GetPhysicsManagerFromScene(Scene);<br><br> if(PhysManager != nullptr)<br> {<br>  PhysManager-&gt;DetachFromPhysScene(Scene);<br>  delete PhysManager;<br>  PhysManager = nullptr;<br> }<br>}</pre><p>For each scene, the manager creates the <em>Chaos</em> sim-callback object (FSWPAsyncCallback) and registers it on the OnPreSimulate_Internal path, where the physics step runs. In addition, it hooks two Game-Thread points to prepare and consume simulation data: ScenePreTick and ScenePostTick.</p><pre>FSWPAsyncPhysicsManager::FSWPAsyncPhysicsManager(FPhysScene* InPhysScene)<br> : PhysScene(*InPhysScene), AsyncObject(nullptr)<br>{<br> if(!bInitialized)<br> {<br>  OnPostWorldInitializationHandle = FWorldDelegates::OnPostWorldInitialization.AddStatic(&amp;FSWPAsyncPhysicsManager::OnPostWorldInitialization);<br>  OnWorldCleanupHandle = FWorldDelegates::OnWorldCleanup.AddStatic(&amp;FSWPAsyncPhysicsManager::OnWorldCleanup);<br><br>  bInitialized = true;<br> }<br><br> FSWPAsyncPhysicsManager::SceneToPhysicsManagerMap.Add(InPhysScene, this);<br>}<br><br>void FSWPAsyncPhysicsManager::OnPostWorldInitialization(UWorld* InWorld, const UWorld::InitializationValues)<br>{<br> FSWPAsyncPhysicsManager* AsyncTickManager = FSWPAsyncPhysicsManager::GetPhysicsManagerFromScene(InWorld-&gt;GetPhysicsScene());<br><br> if(AsyncTickManager != nullptr)<br> {<br>  AsyncTickManager-&gt;RegisterCallbacks();<br> }<br>}<br><br>void FSWPAsyncPhysicsManager::RegisterCallbacks()<br>{<br> OnPhysScenePreTickHandle = PhysScene.OnPhysScenePreTick.AddRaw(this, &amp;FSWPAsyncPhysicsManager::ScenePreTick);<br> OnPhysScenePostTickHandle = PhysScene.OnPhysScenePostTick.AddRaw(this, &amp;FSWPAsyncPhysicsManager::ScenePostTick);<br> <br> if(AsyncObject == nullptr)<br> {<br>  AsyncObject = PhysScene.GetSolver()-&gt;CreateAndRegisterSimCallbackObject_External&lt;FSWPAsyncCallback&gt;();<br> }<br>}</pre><p>When a vehicle is created, it retrieves its FPhysScene, looks up the manager, and registers with it.</p><pre>void ASWPVehicle::BeginPlay()<br>{<br> Super::BeginPlay();<br><br> if (GetWorld())<br> {<br>  if (FPhysScene* PhysScene = GetWorld()-&gt;GetPhysicsScene())<br>  {<br>   if (FSWPAsyncPhysicsManager* PhysManager = FSWPAsyncPhysicsManager::GetPhysicsManagerFromScene(PhysScene))<br>    Guid = PhysManager-&gt;AddVehicle(this);<br>  }<br> }<br>}</pre><h4>Data exchange between the Game Thread and the Physics Thread</h4><p>The Game Thread (GT) and the Physics Thread (PT) run in parallel. Data is <strong>not</strong> exchanged by directly accessing objects owned by the other thread, but via Chaos-managed buffers — FSimCallbackInput/FSimCallbackOutput—consumed inside a TSimCallbackObject. This mechanism uses <strong>lock-free queues</strong> to move packets between threads at specific points in the frame.</p><p>(See: <a href="https://dev.epicgames.com/documentation/en-us/unreal-engine/API/Runtime/Chaos/TSimCallbackObject">https://dev.epicgames.com/documentation/en-us/unreal-engine/API/Runtime/Chaos/TSimCallbackObject</a>)</p><p><strong>Why avoid direct access to UObjects?</strong></p><p>UObject are <strong>not thread-safe</strong>. Accessing them from a thread other than the Game Thread can lead to:</p><ul><li><strong>Garbage Collection (GC) hazards:</strong> the GC runs on the Game Thread and might destroy an object while another thread (the physics simulation, in our case) is trying to dereference it.</li><li>Concurrent writes/<strong>data races</strong>: multiple threads writing a property at the same time can corrupt state.</li><li>Ordering assumptions/<strong>race conditions</strong>: some logic only holds with a specific read/write order that concurrent execution does not guarantee.</li></ul><p>In this plugin, <strong>vehicle settings</strong> (e.g., suspension parameters, force limits) live on the <strong>Pawn</strong> on the <strong>Game Thread</strong>, while the <strong>simulation</strong> and its <strong>internal state</strong> live on the <strong>Physics Thread</strong>.<br>For thread-safety, the Physics Thread <strong>never dereferences the Pawn</strong>, and therefore cannot read values from it directly.</p><p>Instead, GT ↔ PT synchronization uses a <strong>globally unique vehicle identifier</strong>: FGuid.<br>FGuid is a 128-bit identifier (4 × uint32) provided by the <em>UE</em> APIs. It is generated by the manager when a new vehicle spawns and stays attached to that vehicle for its entire lifetime.</p><pre>FGuid FSWPAsyncPhysicsManager::AddVehicle(TWeakObjectPtr&lt;ASWPVehicle&gt; Vehicle)<br>{<br> if (Vehicle.IsValid())<br> {<br>  FGuid Guid = FGuid::NewGuid();<br>   <br>  Vehicles.Add(Vehicle);<br>  VehiclesToAdd.Add(Guid);<br>  <br>  return Guid;<br> }<br><br> return FGuid();<br>}</pre><p>This identifier lets us correlate the same vehicle <strong>across two separate maps living on different threads</strong>.<br>On the <strong>Game Thread</strong>, it maps the vehicle to its <strong>configuration</strong>; on the <strong>Physics Thread</strong>, it maps the same vehicle to its <strong>simulation state</strong>.</p><p>It’s essential to keep both maps <strong>in sync</strong>: whenever a vehicle is created or removed, the corresponding FGuid must be added or removed on the Physics Thread as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1vDkRvD_Es8pSQU3nTNF3Q.png" /></figure><p>This strategy keeps the plugin’s workflow <strong>fully aligned with <em>Unreal Engine 5</em> guidelines and best practices</strong>.</p><h4><strong>Physics step and parallelization with Chaos::PhysicsParallelFor</strong></h4><p>The core of the simulation lives in theFSWPAsyncCallback::OnPreSimulate_Internal() method.</p><p>At each step:</p><ol><li><strong>Consume inputs:</strong> read the snapshot prepared in ScenePreTick().</li><li><strong>Align state:</strong> update the vehicle map.</li><li><strong>Body reference:</strong> obtain the vehicle’s rigid handle (FPBDRigidParticleHandle*).</li><li><strong>Compute forces:</strong> for each suspension compute compression, damping, and the resulting force.</li><li><strong>Apply forces:</strong> apply those forces to the rigid handle at the correct locations.</li></ol><p>Because each vehicle is <strong>independent</strong>, this is a perfect fit for parallelization. To do that, I use:</p><pre>Chaos::PhysicsParallelFor(int32 InNum,<br>                          TFunctionRef&lt;void(int32)&gt; InCallable,<br>                          bool bForceSingleThreaded = false);</pre><p>This function performs the <strong>same operation N times</strong>, distributing work across the <strong>physics worker threads</strong>. It returns <strong>only after all iterations have completed</strong>.</p><p>Inside the lambda (TFunctionRef&lt;void(int32)&gt; InCallable), each iteration touches <strong>only its own vehicle’s data</strong>. Since each worker operates on a disjoint memory region, <strong>no locks or shared structures</strong> are needed. As a final step, the computed forces are applied to the vehicle’s rigid handle.</p><pre>SCOPE_CYCLE_COUNTER(STAT_SmokinWheelsPhx_ChaosParallelFor);<br>  {<br>   Chaos::PhysicsParallelFor(NumVehicles, [World, SimTime, Configs, PhysicsData, Outs, this](int32 i)<br>   {<br>    FSWPVehiclePhysicsData* VehiclePhysicsData = PhysicsData[i];<br>    if (!VehiclePhysicsData) return;<br><br>    const FSWPVehicleConfig&amp; VehicleConfig = Configs[i];<br>    FSWPVehicleState&amp; VehicleSimState = VehiclePhysicsData-&gt;SimState;<br>    <br>    Chaos::FPBDRigidParticleHandle* Chassis = VehiclePhysicsData-&gt;PhysicsHandle;<br>    if (!Chassis) return;<br><br>    FSWPVehicleOut&amp; VehicleOut = Outs[i];<br>    VehicleOut.Guid = VehicleConfig.Guid;<br><br>    const FTransform ChassisTransformWorld = FTransform(Chassis-&gt;GetR(), Chassis-&gt;GetX());<br><br>    FSWPSuspensionSolver::Compute(World,<br>     VehicleConfig.VehicleActor,<br>     ChassisTransformWorld,<br>     VehicleConfig.FrontLeftSuspension,<br>     VehicleSimState.FrontLeftSuspension,<br>     VehicleOut,<br>     SimTime);<br>    FSWPSuspensionSolver::Compute(World,<br>     VehicleConfig.VehicleActor,<br>     ChassisTransformWorld,<br>     VehicleConfig.FrontRightSuspension,<br>     VehicleSimState.FrontRightSuspension,<br>     VehicleOut,<br>     SimTime);<br>    FSWPSuspensionSolver::Compute(World,<br>     VehicleConfig.VehicleActor,<br>     ChassisTransformWorld,<br>     VehicleConfig.RearLeftSuspension,<br>     VehicleSimState.RearLeftSuspension,<br>     VehicleOut,<br>     SimTime);<br>    FSWPSuspensionSolver::Compute(World,<br>     VehicleConfig.VehicleActor,<br>     ChassisTransformWorld,<br>     VehicleConfig.RearRightSuspension,<br>     VehicleSimState.RearRightSuspension,<br>     VehicleOut,<br>     SimTime);<br>    <br>    FSWPPhysicsUtility::AddForceAtLocation(Chassis,<br>     VehicleSimState.FrontLeftSuspension.ForceLocation,<br>     VehicleSimState.FrontLeftSuspension.Fz * 100.0f);<br>    FSWPPhysicsUtility::AddForceAtLocation(Chassis,<br>     VehicleSimState.FrontRightSuspension.ForceLocation,<br>     VehicleSimState.FrontRightSuspension.Fz * 100.0f);<br>    FSWPPhysicsUtility::AddForceAtLocation(Chassis,<br>     VehicleSimState.RearLeftSuspension.ForceLocation,<br>     VehicleSimState.RearLeftSuspension.Fz * 100.0f);<br>    FSWPPhysicsUtility::AddForceAtLocation(Chassis,<br>     VehicleSimState.RearRightSuspension.ForceLocation,<br>     VehicleSimState.RearRightSuspension.Fz * 100.0f);<br>   }, false);<br>  }</pre><h4>A small UI to put the plugin through its paces</h4><p>To validate the plugin’s behavior, I built a <strong>utility UI</strong> — essentially a test harness: minimal, no frills — designed to stress <strong>GT ↔ PT</strong> flows and verify the architecture under typical conditions.</p><p>Usage is simple: press <strong>K</strong> to spawn a vehicle. The manager assigns it an FGuid, and the ID appears in the list view at the top right.</p><p>Each list row also exposes a <strong>Destroy</strong> button. Pressing it removes the vehicle on the Game Thread and queues its FGuid for removal on the Physics Thread in the next step. Being able to <strong>add/remove instances at runtime</strong>, in any order and at high frequency, without crashes or desyncs, is practical proof that the Game Thread and Physics Thread maps remain aligned using only FGuid as the synchronization key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pJuXRWOUy-ni7VVQeQB5eQ.gif" /></figure><p>You can directly <strong>select</strong> the vehicle,<strong> click on it</strong>, to open a tuning panel and <strong>tweak its parameters</strong> (<em>travel, stiffness, bump/rebound, max force</em>) in real time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G3xnUdhB8lobtDomoovvaw.gif" /></figure><p>These changes never touch the Physics Thread directly: they’re written to Game Threads inputs and applied by the Physics Thread on the next step, so you immediately see suspension response and debug lines without violating thread-safety.</p><h4>Profiling the plugin’s performance</h4><p>The plugin provides a few helpful commands to trace simulation performance and the impact of concurrency.<br> I defined <strong>five metrics</strong> to analyze the simulation and how multithreading affects it:</p><ul><li><strong>SmokinWheelsPhx:OnPreSimulate_Internal</strong> — measures the runtime of the entire vehicle simulation method. This includes data-structure synchronization with the Game Thread, resolving each vehicle’s FPBDRigidParticleHandle, computing per-wheel suspension forces, and applying those forces.</li><li><strong>SmokinWheelsPhx:ChaosParallelFor</strong> — measures the scope that computes suspension forces and applies them <strong>when parallelization is enabled</strong>.</li><li><strong>SmokinWheelsPhx:ChaosSingleThread</strong> — measures the same scope <strong>when forced to run single-threaded</strong>.</li><li><strong>SmokinWheelsPhx:ScenePreTick</strong> — measures the preparation of the <strong>Input</strong> buffer that will be passed to physics.</li><li><strong>SmokinWheelsPhx:ScenePostTick</strong> — measures the consumption of the <strong>Output</strong> buffer coming back from physics.</li></ul><p>To visualize these counters, run this in the UE5 console:</p><pre>stat SmokinWheelsPhx</pre><p>To toggle single-thread execution at runtime:</p><pre>swp.ForceSingleThread true    // enable single-thread path<br>swp.ForceSingleThread false   // use Chaos::PhysicsParallelFor</pre><h4>Results analysis</h4><p>It’s a common misconception that introducing concurrency immediately boosts FPS. Not exactly. Concurrency typically improves <strong>scalability</strong> and <strong>stability</strong>, but FPS depends on where the <strong>bottleneck</strong> is.</p><p>Frame rate is limited by the <strong>slowest stage</strong> among Game, Render, GPU, and Physics. If the bottleneck is, say, the <strong>Render Thread</strong> or the <strong>GPU</strong>, shaving milliseconds off the Physics Thread won’t raise FPS.</p><p>Moreover, with <strong>async physics</strong> the Physics Thread runs at a fixed frequency <strong>off</strong> the Game Thread. You can reduce PT time and still see <strong>no FPS increase</strong>, because the frame rate is dictated by Game/Render/GPU. The real gains are:</p><ul><li>the ability to handle <strong>more vehicles at the same FPS</strong> (scalability), and</li><li><strong>fewer hitches/spikes</strong> when work bursts happen at awkward moments (stability).</li></ul><p>There’s also <strong>multithreading overhead</strong> to consider. Concurrency has a cost: task scheduling, work distribution, and any per-frame setup you perform for the workers. This overhead is often small, but it depends on how you prepare and launch the jobs.</p><p>As a rule of thumb, when you only have a <strong>handful of vehicles</strong>, a <strong>single thread</strong> can be faster than spinning up concurrent workers.</p><p>Finally, some operations are <strong>not parallelizable</strong> in practice. Certain APIs take <strong>locks</strong> or touch <strong>shared data structures</strong>, forcing threads to wait. Putting those calls inside a ParallelFor() block yields <strong>no performance benefit</strong> (and can even make things worse).</p><p>In the screenshots below, the simulation runs<strong> 230 vehicles </strong>on an<strong> i7–11700KF @ 3.60 GHz, 32 GB RAM, </strong>and a <strong>GeForce RTX 3070 Ti.</strong></p><ul><li><strong>Single-thread</strong>: <strong>78.87 FPS</strong> → 12.68 ms<strong> </strong>per frame</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L81KSxcX2ll8VM3YDAulSA.png" /></figure><ul><li><strong>Multithreaded</strong> (Chaos::PhysicsParallelFor): <strong>88.19 FPS</strong> → 11.34 ms/frame (<strong>+11.8%</strong>, ~<strong>–1.34 ms</strong> per frame)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bT-rIzUGpQB-gV2Nh_wydw.png" /></figure><p>The uplift is noticeable, but keep in mind this scenario currently simulates <strong>only simple suspensions</strong>, and certain calls — e.g., <strong>line traces via </strong>UWorld—may impose internal locks that limit parallel scaling.</p><p>As the simulation grows (adding a <strong>tire model</strong>, <strong>powertrain, </strong>etc.), more of the workload can shift onto the physics workers, and the benefit from concurrency <strong>should increase further</strong>.</p><h4>Closing thoughts</h4><p>This project started with a single car and ended with a fleet — each vehicle simulated on the Physics Thread, cleanly decoupled from the Game Thread, and scheduled per scene through a focused plugin.</p><p>This isn’t just about “putting more vehicles on screen.” The plugin demonstrates a <strong>reusable architectural pattern</strong> for managing vehicles in UE5 that you can carry into any future project.</p><p>Along the way we locked down a few principles that make the whole system robust:</p><ul><li><strong>Per-scene ownership:</strong> one manager per FPhysScene, no global singletons, no cross-talk.</li><li><strong>GT ↔ PT contract:</strong> Game Thread writes <strong>Input</strong>, Physics Thread writes <strong>Output</strong>. No UObjects on the Physics Thread.</li><li><strong>Multithreading that matters:</strong> Chaos::PhysicsParallelFor scales the physics step; it boosts <strong>capacity and stability</strong> first — <strong>FPS</strong> only if physics is your bottleneck.</li></ul><p>If you want to explore or adapt these ideas, clone the repo linked below and poke at the code: spawn vehicles, flip the single-thread flag, profile, and try your own workloads. I’d love to see what you build — especially if you push the system with richer tire dynamics or networked play.</p><p>👉 <a href="https://github.com/fgrenoville/Async-Physics-Suspension-MT">Source code on GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d322b2b94001" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/from-one-car-to-a-fleet-asynchronous-physics-in-ue5-that-scales-with-multithreading-d322b2b94001">From one car to a fleet: asynchronous physics in UE5 that scales with multithreading</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Taming Chaos: Stable Vehicle Suspensions with Async Physics in UE5]]></title>
            <link>https://levelup.gitconnected.com/taming-chaos-stable-vehicle-suspensions-with-async-physics-in-ue5-566369c7b097?source=rss-fe9a23aaa782------2</link>
            <guid isPermaLink="false">https://medium.com/p/566369c7b097</guid>
            <category><![CDATA[unreal-engine-5]]></category>
            <category><![CDATA[vehicle-suspension]]></category>
            <category><![CDATA[chaos-physics]]></category>
            <dc:creator><![CDATA[Federico Grenoville]]></dc:creator>
            <pubDate>Wed, 24 Sep 2025 03:18:33 GMT</pubDate>
            <atom:updated>2025-09-24T03:18:33.647Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*McQNASIPXC9UEVn7P32Pnw.png" /></figure><p>Has it ever happened to you that a car in a video game suddenly starts vibrating, bouncing, or even flying away uncontrollably?</p><p>That’s the classic symptom of a physics simulation tied to the frame rate, or the use of a “wrong” integrator.<br>In this article, I’ll show you how to avoid this in <strong>Unreal Engine 5</strong> by leveraging<em> Chaos’ asynchronous physics</em>, with a concrete example: a car with suspensions designed for a racing game.</p><h4><strong>The problem: numerical stability</strong></h4><p>When working with real-time physics, the first challenge is numerical stability. To get reliable simulations, you need a <strong><em>semi-implicit Euler</em></strong> integrator with the smallest possible delta time.<br>The smaller the delta time, the smaller the numerical error — until it becomes negligible.</p><p>The problem is that the game tick doesn’t guarantee this. If the frame rate drops — for example, due to a sudden increase in rendered objects or a hardware slowdown — the delta time grows, and the physics simulation can become unstable. In the worst cases, physics can literally “explode.”</p><p>With <em>Unreal Engine 5</em>, Epic introduced the <em>Chaos </em>physics engine, which provides an elegant solution: the ability to run the simulation in a separate thread, independent from the game tick. This way, we can maintain a constant delta time and achieve much more robust simulations.</p><p>If you’d like to dive deeper into the theory and understand why spring-damper systems can become unstable in game engines, <a href="https://medium.com/gitconnected/tick-by-tick-how-unreal-engine-simulates-real-world-physics-4ac7bc9ee5fb"><strong>check out my previous article here</strong></a>.<br> That’s the conceptual foundation this project is built on.</p><h4>Example project: car suspensions</h4><p>To illustrate how to use asynchronous physics in UE5, I’ll use a project that simulates the behavior of car suspensions.</p><p>Suspensions are simulated with a <strong><em>line trace</em></strong>:</p><p>· from the point where the suspension attaches to the chassis (TopLink),</p><p>· downward (local suspension direction),</p><p>· for a length equal to the suspension travel plus the wheel radius (both are configurable parameters we’ll analyze later).</p><p>From the ground contact we derive:</p><p>· spring compression,</p><p>· shock absorber damping,</p><p>· and finally the net force the suspension applies to the chassis.</p><p>Modeling a suspension in a simplified way allows us to keep the focus of this article on asynchronous physics, without complicating the project with details that aren’t relevant here.</p><p>Even though this suspension doesn’t implement real kinematics (like double wishbone or MacPherson), it’s still a valid technique used in many arcade racing games. Moreover, it’s the perfect example of a <strong><em>spring-damper system</em></strong>, which we’ve previously seen can cause all sorts of issues in game engines.</p><h4><strong>Project organization</strong></h4><p>The project follows a <strong>Composition pattern</strong>:</p><p>· The <strong><em>pawn</em></strong> represents the vehicle. It’s composed of a static mesh and four Suspension components.</p><p>· The <strong><em>static mesh</em></strong> represents the chassis. In Unreal Engine, a <em>static mesh</em> can act as a rigid body (with mass, inertia tensor, and other physical properties). This is where we’ll apply the calculated forces.</p><p>· The <strong><em>suspension component</em></strong>, derived from <em>SceneComponent</em>, can be positioned spatially in a specific point of the <em>pawn</em>, slightly above the wheels. It defines the TopLink point.</p><p>Each Suspension exposes a few key properties:</p><p>· <strong>TravelCm</strong> — maximum length of the <em>line trace</em>. If it’s too short, the suspension might not “see” the ground.</p><p>· <strong>SpringStiffness</strong> — the spring constant (<em>Hooke</em>’s law), i.e. suspension stiffness.</p><p>· <strong>ShockBump and ShockRebound</strong> — damping coefficients in compression and rebound. They allow different responses, improving vehicle controllability.</p><p>· <strong>MaxForce</strong> — the maximum force the suspension can apply, to avoid unwanted force spikes in edge cases.</p><p>· <strong>WheelRadiusCm</strong> — the actual radius of the wheel mesh, added to TravelCm to visually separate wheel and suspension movement.</p><pre>UCLASS(ClassGroup = (AsyncPhxSuspension))<br>class ASYNCPHXSUSPENSION_API AVehicle : public APawn<br>{<br> GENERATED_BODY()<br><br>public:<br> AVehicle();<br><br>private: <br> UPROPERTY(EditAnywhere, Category = &quot;AsyncPhxSuspension&quot;)<br> TObjectPtr&lt;UStaticMeshComponent&gt; BodyMeshComponent; <br> <br> UPROPERTY(EditAnywhere, Category = &quot;AsyncPhxSuspension&quot;)<br> TObjectPtr&lt;USuspension&gt; FrontLeftSuspension;<br> UPROPERTY(EditAnywhere, Category = &quot;AsyncPhxSuspension&quot;)<br> TObjectPtr&lt;USuspension&gt; FrontRightSuspension;<br> UPROPERTY(EditAnywhere, Category = &quot;AsyncPhxSuspension&quot;)<br> TObjectPtr&lt;USuspension&gt; RearLeftSuspension;<br> UPROPERTY(EditAnywhere, Category = &quot;AsyncPhxSuspension&quot;)<br> TObjectPtr&lt;USuspension&gt; RearRightSuspension; <br>};<br><br>UCLASS(ClassGroup = (AsyncPhxSuspension), meta = (BlueprintSpawnableComponent))<br>class ASYNCPHXSUSPENSION_API USuspension : public USceneComponent<br>{<br> GENERATED_BODY()<br><br>public:<br> UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = &quot;AsyncPhxSuspension&quot;)<br> float TravelCm;<br> UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = &quot;AsyncPhxSuspension&quot;)<br> float SpringStiffness;<br> UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = &quot;AsyncPhxSuspension&quot;)<br> float ShockBump;<br> UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = &quot;AsyncPhxSuspension&quot;)<br> float ShockRebound;<br> UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = &quot;AsyncPhxSuspension&quot;)<br> float MaxForce;<br> <br> UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = &quot;AsyncPhxSuspension&quot;)<br> float WheelRadiusCm;<br><br>public:<br> USuspension();<br>};</pre><h4><strong>Enabling asynchronous physics in UE5</strong></h4><p>To enable <em>Chaos </em>in asynchronous mode:</p><p>1. Open <strong><em>Project Settings</em> → <em>Physics</em></strong>.</p><p>2. Enable the <strong><em>Tick Physics Async</em></strong> flag.</p><p>3. Set the physics thread frequency. In this project, it’s set to <strong>1/120</strong> (every 0.0083 ms).</p><p>Some racing sims use frequencies up to <strong>1/400</strong> to get extremely accurate physics. For our purposes, 1/120 is usually a good compromise between accuracy and performance.</p><h4><strong>Game thread vs Physics thread: how they talk to each other</strong></h4><p>The physics thread and the game thread are not synchronized: the physics thread usually runs faster, while the game thread may read data that’s 2–3 frames old.</p><p>To avoid race conditions, <em>Chaos </em>provides two buffers:</p><p>· <strong>Input buffer</strong> → prepared by the game thread before each physics step; typically contains simulation parameters.</p><p>· <strong>Output buffer</strong> → written by the physics thread after executing the step; typically contains results (forces, line traces, debug info).</p><p>This way, the two threads never write to the same data simultaneously.</p><p>In our simulation, the input buffer contains:</p><p>· suspension parameters (TravelCm, SpringStiffness, …): without them, the configuration would remain in the game thread and the simulation wouldn’t adapt to changes,</p><p>· vehicle pointer (<em>AActor</em>): added to the ignore list for the <em>line trace</em>, so the trace doesn’t accidentally hit the car’s own <em>mesh</em>,</p><p>· physics handle: the rigid body in <em>Chaos</em>’ physics world,</p><p>· world pointer: used to perform the <em>line trace</em>. It would be more formal to use <em>Chaos</em>’ own APIs, but they’re less intuitive and don’t support features like ignoring actors or collision layers.</p><pre>struct FAsyncSuspensionIn<br>{<br> FTransform AttachLocal = FTransform();<br><br> float TravelCm = 0.0f;<br> float SpringStiffness = 0.0f;<br> float ShockBump = 0.0f;<br> float ShockRebound = 0.0f;<br> float MaxForce = 0.0f;<br> <br> float WheelRadiusCm = 0.0f;<br>};<br><br>struct ASYNCPHXSUSPENSION_API FAsyncCallbackInput : public Chaos::FSimCallbackInput<br>{<br> UWorld* World = nullptr;<br> AActor* Vehicle = nullptr;<br>  <br> int32 FrameIndex = 0;<br> <br> FPhysicsActorHandle PhxActorHandle;<br><br> FAsyncSuspensionIn FrontLeftSuspension;<br> FAsyncSuspensionIn FrontRightSuspension;<br> FAsyncSuspensionIn RearLeftSuspension;<br> FAsyncSuspensionIn RearRightSuspension;<br><br> void Reset()<br> {<br>  *this = FAsyncCallbackInput();<br> }<br>};</pre><p>The output buffer collects data useful for debugging. We store <em>line traces</em> and force vectors so the game thread can draw them on screen. This way, the user can visually verify that the simulation is working correctly.</p><p>It’s practically impossible to debug a physics simulation step by step with breakpoints. It’s much more meaningful to analyze aggregated values and their behavior over time. That’s why being able to draw force vectors or plot them on a graph is extremely valuable.</p><pre>struct FDebugDrawLineCommand<br>{<br> FVector StartPoint = FVector::ZeroVector;<br> FVector EndPoint = FVector::ZeroVector;<br> FColor Color = FColor::Black;<br> float Thickness = 0.0f;<br> float Duration = 0.0f;<br>};<br><br>struct FAsyncSuspensionOut<br>{<br> static constexpr int32 MaxDebugPerWheel = 8;<br> TArray&lt;FDebugDrawLineCommand, TInlineAllocator&lt;MaxDebugPerWheel&gt;&gt; DebugDrawCommands;<br> <br> FORCEINLINE void ClearDebugCommandsBuffer()<br> {<br>#if !UE_BUILD_SHIPPING<br>  {<br>   DebugDrawCommands.Reset();<br>  }<br>#endif<br> }<br><br> FORCEINLINE void AddDebugLineCommand(const FVector&amp; StartPoint, const FVector&amp; EndPoint,<br>  const FColor&amp; Color, const float Thickness, const float Duration)<br> {<br>#if !UE_BUILD_SHIPPING<br>  if (DebugDrawCommands.Num() &gt;= MaxDebugPerWheel) return;<br><br>  DebugDrawCommands.Emplace(FDebugDrawLineCommand{ StartPoint, EndPoint, Color, Thickness, Duration });<br>#endif<br> }<br>};<br><br>struct ASYNCPHXSUSPENSION_API FAsyncCallbackOutput : public Chaos::FSimCallbackOutput<br>{<br> int32 FrameIndex = 0;<br><br> FAsyncSuspensionOut FrontLeftSuspension;<br> FAsyncSuspensionOut FrontRightSuspension;<br> FAsyncSuspensionOut RearLeftSuspension;<br> FAsyncSuspensionOut RearRightSuspension;<br> <br> void Reset()<br> {<br>  *this = FAsyncCallbackOutput();<br> }<br>};</pre><p>Finally, we also define a separate struct that holds the suspension’s internal state. This one is not stored in the buffers but is maintained exclusively by the physics thread, which updates it on every iteration. Since the physics thread runs at a different (usually higher) frequency than the game thread, we can’t put it in the I/O buffers — otherwise, we’d risk not feeding the physics thread with continuous state data.</p><pre>struct FSuspensionState<br>{<br> float PreviousCompressionRatio = 0.0f;<br> <br> float SpringForce = 0.0f;<br> float DampingForce = 0.0f;<br><br> float TotalForce = 0.0f;<br> FVector Fz = FVector::ZeroVector;<br> FVector ForceLocation = FVector::ZeroVector;<br>};</pre><h4><strong>Hooking into Chaos callbacks</strong></h4><p><em>Chaos </em>exposes several callbacks we can extend. They differ mainly in <strong>when</strong> they’re triggered and their purpose: some are called before integration, others after, some during collision resolution, others at the end of the solver execution.</p><p>For our project, we need the callback called <strong>before integration</strong>:</p><p>· Extend the class <em>TSimCallbackObject</em>.</p><p>· Override OnPreSimulate_Internal().</p><p>If <em>substepping </em>is enabled in the <em>project settings</em>, this callback is only triggered on the first step. To catch every substep, you can override OnPreIntegrate_Internal() instead.</p><p>Inside the callback we:</p><p>· use the state struct (<em>SuspensionState</em>),</p><p>· calculate the suspension force,</p><p>· and apply the result to the rigid body via the physics handle.</p><pre>class ASYNCPHXSUSPENSION_API FAsyncCallback : public Chaos::TSimCallbackObject&lt;FAsyncCallbackInput, FAsyncCallbackOutput&gt;<br>{<br>private:<br> FSuspensionState FrontLeftSuspensionState;<br> FSuspensionState FrontRightSuspensionState;<br> FSuspensionState RearLeftSuspensionState;<br> FSuspensionState RearRightSuspensionState;<br> <br>private:<br> virtual void OnPreSimulate_Internal() override;<br> static void AddForceAtLocation(Chaos::FRigidBodyHandle_Internal* RigidHandle, const FVector Location, const FVector Force);<br>};<br><br>void FAsyncCallback::OnPreSimulate_Internal()<br>{<br> const FAsyncCallbackInput* In = GetConsumerInput_Internal();<br> FAsyncCallbackOutput&amp; Out = GetProducerOutputData_Internal();<br><br> if (!In) return;<br><br> const float PhysicsDeltaTime = GetDeltaTime_Internal();<br><br> if (!In-&gt;PhxActorHandle) return;<br>  <br> Chaos::FRigidBodyHandle_Internal* RigidHandle = In-&gt;PhxActorHandle-&gt;GetPhysicsThreadAPI();<br> if (!RigidHandle) return;<br><br> const FTransform VehicleTransformWorld = FTransform(RigidHandle-&gt;R(), RigidHandle-&gt;X());<br><br> Out.FrameIndex = In-&gt;FrameIndex;<br> <br> USuspension::PhysicsTickComponent(In-&gt;World, In-&gt;Vehicle, VehicleTransformWorld, In-&gt;FrontLeftSuspension,<br>  Out.FrontLeftSuspension, FrontLeftSuspensionState, PhysicsDeltaTime);<br> USuspension::PhysicsTickComponent(In-&gt;World, In-&gt;Vehicle, VehicleTransformWorld, In-&gt;FrontRightSuspension,<br>  Out.FrontRightSuspension, FrontRightSuspensionState, PhysicsDeltaTime);<br> USuspension::PhysicsTickComponent(In-&gt;World, In-&gt;Vehicle, VehicleTransformWorld, In-&gt;RearLeftSuspension,<br>  Out.RearLeftSuspension, RearLeftSuspensionState, PhysicsDeltaTime);<br> USuspension::PhysicsTickComponent(In-&gt;World, In-&gt;Vehicle, VehicleTransformWorld, In-&gt;RearRightSuspension,<br>  Out.RearRightSuspension, RearRightSuspensionState, PhysicsDeltaTime);<br> <br> AddForceAtLocation(RigidHandle, FrontLeftSuspensionState.ForceLocation, FrontLeftSuspensionState.Fz * 100.0f);<br> AddForceAtLocation(RigidHandle, FrontRightSuspensionState.ForceLocation, FrontRightSuspensionState.Fz * 100.0f);<br> AddForceAtLocation(RigidHandle, RearLeftSuspensionState.ForceLocation, RearLeftSuspensionState.Fz * 100.0f);<br> AddForceAtLocation(RigidHandle, RearRightSuspensionState.ForceLocation, RearRightSuspensionState.Fz * 100.0f);<br> <br>}<br><br>void FAsyncCallback::AddForceAtLocation(Chaos::FRigidBodyHandle_Internal* RigidHandle, const FVector Location, const FVector Force)<br>{<br> if (!RigidHandle) return;<br><br> const Chaos::FVec3 CoM = Chaos::FParticleUtilitiesGT::GetCoMWorldPosition(RigidHandle);<br> const Chaos::FVec3 Torque = Chaos::FVec3::CrossProduct(Location - CoM, Force);<br> RigidHandle-&gt;AddForce(Force, false);<br> RigidHandle-&gt;AddTorque(Torque, false);<br>}</pre><h4><strong>Completing the vehicle logic</strong></h4><p>In the vehicle class, at BeginPlay():</p><p>· we use the <strong><em>OnPhysScenePreTick</em></strong> delegate to call our HandlePrePhysicsTick() method, which prepares the input buffer before the physics step,</p><p>· we register the physics step callback OnPreSimulate_Internal().</p><p>To avoid memory leaks, it’s essential to deregister both callbacks when they’re no longer needed and the class is being destroyed — a good place to do this is inside EndPlay().</p><pre>void AVehicle::BeginPlay()<br>{<br> Super::BeginPlay();<br><br> CachedWorld = GetWorld();<br> if (!CachedWorld.IsValid()) return;<br><br> if (!IsValid(FrontLeftSuspension) || !IsValid(FrontRightSuspension) ||<br>  !IsValid(RearLeftSuspension) || !IsValid(RearRightSuspension))<br>  return;<br> <br> if (FPhysScene* PhysScene = CachedWorld-&gt;GetPhysicsScene())<br> {<br>  if (!AsyncCallback)<br>  {<br>   AsyncCallback = PhysScene-&gt;GetSolver()-&gt;CreateAndRegisterSimCallbackObject_External&lt;FAsyncCallback&gt;();<br>   PhysScene-&gt;OnPhysScenePreTick.AddUObject(this, &amp;AVehicle::HandlePrePhysicsTick);<br>  }<br> }<br><br> BodyMeshComponent-&gt;SetSimulatePhysics(true);<br> BodyMeshComponent-&gt;SetEnableGravity(true);<br>}<br><br>void AVehicle::EndPlay(const EEndPlayReason::Type EndPlayReason)<br>{<br> if (!CachedWorld.IsValid()) return;<br><br> if (FPhysScene* PhysScene = CachedWorld-&gt;GetPhysicsScene())<br> {<br>  if (AsyncCallback)<br>  {<br>   PhysScene-&gt;GetSolver()-&gt;UnregisterAndFreeSimCallbackObject_External(AsyncCallback);<br>   AsyncCallback = nullptr;<br>  }<br>  <br>  PhysScene-&gt;OnPhysScenePreTick.RemoveAll(this);<br> }<br> <br> Super::EndPlay(EndPlayReason);<br>}</pre><p>To make the whole flow clearer, here’s a summary diagram:</p><ol><li>On the <strong>game thread</strong>, right before the physics step, HandlePrePhysicsTick() is called. This is where we populate the <strong>input buffer</strong> with all the parameters needed for the simulation.</li><li>The <strong>physics thread</strong> runs asynchronously. At the beginning of each step it triggers the OnPreSimulate_Internal() callback, reads from the input buffer, and updates the simulation state.</li><li>At the end of the step, the physics thread writes the results (forces, line traces, debug info) into the <strong>output buffer</strong>.</li><li>On the next Tick() on the game thread, those results are read back and used to update visuals or any gameplay logic that depends on them.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dqRp-yii1BiPoNeJhe2xfA.png" /></figure><p>The diagram highlights the key idea: the two threads <strong>never touch the same data at the same time</strong>. Instead, they exchange information only through dedicated buffers. This pattern prevents race conditions and keeps the simulation stable even when the frame rate fluctuates.</p><p>The <strong>physics thread</strong> runs asynchronously and usually at a <strong>higher frequency</strong> than the game thread. This means it may execute several physics steps using the same data from the input buffer, and it may also write new results to the output buffer more often than the game thread consumes them.<br> It’s up to the <strong>developer</strong> to decide how to synchronize which data should be read or written at any given time. A common approach is to tag buffer updates with <strong>timestamps or frame counters</strong>, so the game thread can always pick the most relevant data and ignore outdated values.</p><h4>How the suspension works</h4><p>Since the Suspension component derives from <em>SceneComponent </em>and doesn’t have a <em>body instance</em> (rigid body), it’s not “seen” by the physics scene.</p><p>Calling GetLocation() would be incorrect because it returns the position known to the game thread, which doesn’t match the actual physics simulation.</p><p>To fix this, on every physics step we read the rigid body transform directly from the physics scene. Because rigid bodies are non-deformable (internal distances between points remain constant), we can multiply the rigid body transform with the suspension’s local-space transform (which never changes). This gives us the correct world-space transform of the suspension component.</p><p>From that position (TopLink), we cast a <em>line trace</em> downward, with a distance equal to TravelCm + WheelRadiusCm.</p><p>If a collision is detected:</p><ul><li>we calculate the shock absorber’s compression ratio,</li><li>apply <em>Hooke</em>’s law to compute the response force,</li><li>project that force onto the impact normal to keep only the vertical component (removing unwanted lateral or forward thrust).</li></ul><p>Finally, we send the data to the output buffer for debugging.</p><pre>void USuspension::PhysicsTickComponent(UWorld* World, AActor* Vehicle, const FTransform AsyncVehicleTransformWorld,<br> const FAsyncSuspensionIn&amp; AsyncSuspensionIn, FAsyncSuspensionOut&amp; AsyncSuspensionOut, FSuspensionState&amp; SuspensionState, float PhysicsDeltaTime)<br>{<br> const FTransform AsyncWorld = AsyncSuspensionIn.AttachLocal * AsyncVehicleTransformWorld;<br> const FQuat AsyncRotation = AsyncWorld.GetRotation();<br><br> FVector AsyncLocation = AsyncWorld.GetLocation();<br> FVector AsyncUp = AsyncRotation.GetUpVector();<br> <br> FCollisionQueryParams TraceParams;<br> TraceParams.MobilityType = EQueryMobilityType::Any;<br> TraceParams.bReturnPhysicalMaterial = false;<br> TraceParams.AddIgnoredActor(Vehicle);<br> TraceParams.bTraceComplex = true;<br><br> SuspensionState.ForceLocation = AsyncLocation;<br> <br> FVector StartTrace = AsyncLocation;<br> FVector EndTrace = StartTrace - AsyncUp * (AsyncSuspensionIn.TravelCm + AsyncSuspensionIn.WheelRadiusCm);<br><br> AsyncSuspensionOut.AddDebugLineCommand(StartTrace, EndTrace, FColor::Magenta, 2.0f, 0.0f);<br><br> FHitResult HitResult;<br><br> if (bool bHasContact = World-&gt;LineTraceSingleByChannel(HitResult, StartTrace, EndTrace, ECC_Visibility, TraceParams))<br> {<br>  const FVector TraceVector = HitResult.ImpactPoint - StartTrace;<br>  const float HitDistanceInSuspensionAxis = FVector::DotProduct(TraceVector, -AsyncUp);<br><br>  const float CompressionRatio = FMath::Clamp(1.0f - (HitDistanceInSuspensionAxis / (AsyncSuspensionIn.TravelCm + AsyncSuspensionIn.WheelRadiusCm)), 0.0f, 1.0f);<br>  const float CompressionVelocity = (CompressionRatio - SuspensionState.PreviousCompressionRatio) / PhysicsDeltaTime;<br>  <br>  const float SpringForce = CompressionRatio * AsyncSuspensionIn.SpringStiffness;<br>  <br>  const float DampingForce = CompressionVelocity &gt; 0.0f ?<br>   CompressionVelocity * AsyncSuspensionIn.ShockBump :    // Compression<br>     CompressionVelocity * AsyncSuspensionIn.ShockRebound;  // Extension<br><br><br>  const float TotalForce = FMath::Clamp(SpringForce + DampingForce, 0.0f, AsyncSuspensionIn.MaxForce);<br>  const FVector Fz = TotalForce * AsyncUp;<br>  const FVector Fn = FMath::Max(0.0f, FVector::DotProduct(Fz, HitResult.ImpactNormal)) * HitResult.ImpactNormal;<br>  <br>  SuspensionState.PreviousCompressionRatio = CompressionRatio;<br>  SuspensionState.SpringForce = SpringForce;<br>  SuspensionState.DampingForce = DampingForce;<br>  SuspensionState.Fz = Fn;<br><br>  AsyncSuspensionOut.AddDebugLineCommand(SuspensionState.ForceLocation,<br>   SuspensionState.ForceLocation + SuspensionState.Fz * ScaleDrawingForce, FColor::Emerald,<br>   3.5f, 0.0f);<br> }<br> else<br> {<br>  SuspensionState.PreviousCompressionRatio = 0.0f;<br>  SuspensionState.SpringForce = 0.0f;<br>  SuspensionState.DampingForce = 0.0f;<br>  SuspensionState.Fz = FVector::ZeroVector;<br> }<br>}</pre><h4><strong>The result</strong></h4><p>The car is convincingly supported by its four suspensions, just like in reality. The suspensions react when stressed and stabilize the vehicle effectively.</p><p>The UI panel (top-right) allows you to tweak the parameters of each suspension in real time. This is possible thanks to the proper management of input/output buffers: values are read, written, and synchronized with the simulation in separate, well-defined stages. Without this pattern, changing parameters would likely cause the simulation to crash.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JCGtCeP3gITDWB2akXpzsw.gif" /></figure><h4>Alternative: the AsyncTickPhysics plugin</h4><p>Using asynchronous physics in UE5 inevitably requires C++ code and a good understanding of delegates.<br> If the goal is to simplify the workflow or work directly in Blueprint, there are plugins that expose the async tick without having to manage callbacks and buffers manually.</p><p>One of the most well-known is <a href="https://github.com/Mr-Craig/AsyncTickPhysics"><strong>AsyncTickPhysics</strong></a>.</p><h4>How the plugin works</h4><p>The plugin uses the <strong>Singleton pattern</strong> to implement the <em>AsyncTickManager</em>.<br> This manager registers physics scene callbacks and keeps a list of <em>pawns</em> and <em>ActorComponents</em>, on which it calls NativeAsyncTick().</p><p>To use it, you derive from one of two classes:</p><ul><li><em>AsyncTickPawn</em></li><li><em>AsyncTickActorComponent</em></li></ul><p>At BeginPlay(), these automatically register with the manager.</p><p>From there, you just override:</p><ul><li>NativeAsyncTick() in C++,</li><li>or AsyncTick() in Blueprint,<br> to define your async physics code.</li></ul><h4>Caveats when using the plugin</h4><p>The plugin doesn’t use <em>Chaos</em>’ input/output buffer system for exchanging data between physics and game threads. That means any read/writes inside AsyncTick() are more exposed to <strong>race conditions</strong>, or worse, crashes.</p><p>On top of that, the plugin hasn’t been updated since 2022, and the author is no longer active on Epic’s forum thread: <a href="https://forums.unrealengine.com/t/exposing-ue5-tickphysicsasync-event/271744/3">link</a>.</p><p>For these reasons, I consider AsyncTickPhysics useful for prototyping or quick tests, but not reliable for production or commercial projects.</p><h4>Conclusions and resources</h4><p>We started by talking about numerical stability and why the game tick alone can’t guarantee reliable physics. From there, we explored <em>Chaos</em>, Unreal Engine 5’s new physics engine, which allows running simulations in a dedicated thread, independent of the frame rate.</p><p>With a deliberately simple suspension model, we’ve seen step by step how to:</p><ul><li>organize the vehicle components,</li><li>use input/output buffers to communicate between threads,</li><li>hook into the right <em>Chaos </em>callbacks,</li><li>and visualize results clearly for debugging.</li></ul><p>The result is a car that behaves convincingly, with reactive suspensions and parameters you can tweak in real time, without the usual frame-rate-dependent issues.</p><p>Of course, this is only the beginning. From here you could extend the model with more complex kinematics (double wishbone, MacPherson), add wheel-terrain friction dynamics, or even build a fully custom vehicle physics system.</p><p>Whether you’re building a quick prototype, an arcade racer, or a more realistic simulator, <em>Chaos</em>’ asynchronous approach gives you a solid foundation for stable, scalable physics.</p><p>Want to see all this in action? I’ve made the full source code available on GitHub: clone it, test it, and have fun tweaking parameters and callbacks to see how the simulation behaves.<br> 👉<a href="https://github.com/fgrenoville/Async-Physics-Suspension"> Source code on GitHub</a></p><p>This is just a starting point: if you use it as a base for your own experiments, share what you’ve built in the comments — it might inspire other readers too!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=566369c7b097" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/taming-chaos-stable-vehicle-suspensions-with-async-physics-in-ue5-566369c7b097">Taming Chaos: Stable Vehicle Suspensions with Async Physics in UE5</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tick by Tick: How Unreal Engine Simulates Real-World Physics]]></title>
            <link>https://levelup.gitconnected.com/tick-by-tick-how-unreal-engine-simulates-real-world-physics-4ac7bc9ee5fb?source=rss-fe9a23aaa782------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ac7bc9ee5fb</guid>
            <category><![CDATA[substepping]]></category>
            <category><![CDATA[unreal-engine]]></category>
            <category><![CDATA[game-engine]]></category>
            <category><![CDATA[async-physics-tick]]></category>
            <category><![CDATA[physics]]></category>
            <dc:creator><![CDATA[Federico Grenoville]]></dc:creator>
            <pubDate>Mon, 30 Jun 2025 01:32:00 GMT</pubDate>
            <atom:updated>2025-06-30T07:27:12.329Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*St_5bJi0U5Bzbej38Odijw.png" /></figure><p>If you’ve ever wondered what powers the physics engine in Unreal Engine, and what terms like <strong><em>integration</em></strong>, <strong><em>substepping</em></strong>, or <strong><em>async transform</em></strong> really mean, you’re in the right place!</p><p>In a game engine, the physics engine simulates the objects’ physical behavior within the scene, making their interactions more realistic. Its main functions include:</p><p>· <strong><em>Rigid body dynamics</em></strong> — Manages the motion and collisions of solid objects based on physical laws.</p><p>· <strong><em>Collision detection</em></strong> — Determines when and where two objects touch in space.</p><p>· <strong><em>Collision response</em></strong> — Decides what happens as a result of a contact.</p><p>· <strong><em>Constraint and joint handling</em></strong> — Allow connections between objects, which may be rigid or flexible.</p><p>· <strong><em>Soft body physics</em></strong> — Simulates deformable materials.</p><h4><strong>How does the physics engine compute all this?</strong></h4><p>At the core of it all lie the concepts of <strong><em>position</em></strong>, <strong><em>velocity</em></strong>, and <strong><em>acceleration</em></strong>.</p><p>From classical Newtonian mechanics, we know that to change an object’s state, we need to apply a force.<br> A force generates an acceleration, which changes the velocity, which in turn alters the position.</p><p>We can say that <strong>velocity is the derivative of position over time</strong>, and <strong>acceleration is the derivative of velocity over time</strong>.<br> To compute how position and velocity evolve over time, we need to solve two differential equations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/189/1*NSg_HILtZsMGYDKQ4VJueg.png" /></figure><p>Around 1768, Euler developed a simple method to estimate solutions without complex math involved.</p><p>Based on the definition of a derivative as a rate of change, the idea is: if you know a function’s value at a given time, you can use its derivative to predict where it will be a moment later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qxsQ5KGf9vQgHW0g.png" /></figure><p>This numerical method of solving differential equations is ideal for use in game engines, as it’s simple, light, and aligns well with the concept of updating systems each frame (i.e., during the tick).</p><p>Assuming the delta time of the tick as our time step, the formulas become:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*_lfDQQI4wTEdKclVe4WXZg.png" /></figure><p>This is known as the <strong><em>explicit Euler method</em></strong>, applied to velocity and position. It’s called explicit because the new state — like position or velocity — is computed directly using only known values from the current step. There’s no need to solve complex equations or work backwards from unknowns.</p><h4><strong>Frame Rate and Simulation</strong></h4><p>One of the fundamental concepts in a game engine is the <strong><em>frame rate</em></strong>.</p><p>Frame rate (measured in <strong><em>FPS</em></strong>) defines how fast the scene is updated.</p><p>The higher the FPS, the smoother the visuals. A typical ideal frame rate is 60 FPS, meaning the scene updates 60 times per second, or once every 0.016 seconds (1/60).</p><p>Unreal can operate in two modes:</p><p>· <strong><em>Variable frame rate</em></strong></p><p>· <strong><em>Fixed frame rate</em></strong></p><p>In <strong><em>variable frame rate</em></strong> mode, the delta time between frames varies depending on the system’s performance. This ensures the game runs in real time, regardless of hardware capabilities.</p><p>In <strong><em>fixed frame rate</em></strong> mode, Unreal tries to maintain a constant delta time. If the hardware can keep up, the simulation remains real time — 1 second simulated equals 1 second real time.</p><p>However, if the system can’t maintain the target frame rate, Unreal will still simulate using the fixed delta time, even if more time has passed.</p><p>As a result, the simulation slows down, since less simulated time is processed per real time second — breaking real-time behavior.</p><p>The frame rate setting can be found in the “<strong><em>Project Settings”</em></strong> under “<strong><em>Engine” </em></strong>→ “<strong><em>General Settings”</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DIcKC-_8fLMFKEOsMKD5XA.png" /></figure><h4><strong>Explicit Euler Integration in Action</strong></h4><p>Let’s build an actor that moves its mesh using <strong><em>explicit Euler integration</em></strong>.</p><p>We’ll perform calculations inside the <em>tick</em> function, linking the Euler step size to the delta time passed as a parameter.</p><pre>UCLASS()<br>class PHYSICSPLAYGROUND_API AExplicitEulerTick : public AActor<br>{<br> GENERATED_BODY()<br><br>public:<br> UPROPERTY(EditAnywhere)<br> FVector Force;<br> UPROPERTY(EditAnywhere)<br> float Mass;<br> UPROPERTY(EditAnywhere)<br> float TotalTime;<br> UPROPERTY(VisibleAnywhere)<br> float Accumulator;<br><br> UPROPERTY(EditAnywhere)<br> TObjectPtr&lt;UStaticMeshComponent&gt; StaticMesh;<br><br>public:<br> AExplicitEulerTick();<br> virtual void Tick(float DeltaTime) override;<br> <br>protected:<br> virtual void BeginPlay() override;<br><br>private:<br> const float ToUnrealForceUnits = 100.0f;<br> <br> FVector StartLocation;<br> FVector Position;<br> FVector Velocity;<br><br> bool Stop;<br> int32 TickCount;<br> double StartTime;<br>};</pre><pre>AExplicitEulerTick::AExplicitEulerTick()<br>{<br> PrimaryActorTick.bCanEverTick = true;<br><br> StaticMesh = CreateDefaultSubobject&lt;UStaticMeshComponent&gt;(&quot;StaticMesh&quot;);<br> StaticMesh-&gt;SetupAttachment(RootComponent);<br>}<br><br>void AExplicitEulerTick::BeginPlay()<br>{<br> Super::BeginPlay();<br><br> StaticMesh-&gt;SetSimulatePhysics(false);<br><br> TickCount = 0;<br> Accumulator = 0.0f;<br> Position = StartLocation = GetActorLocation();<br> Velocity = FVector::ZeroVector;<br> Stop = false;<br> StartTime = FPlatformTime::Seconds();<br>}<br><br>void AExplicitEulerTick::Tick(float DeltaTime)<br>{<br> Super::Tick(DeltaTime);<br><br> const FVector Acceleration = (Force * ToUnrealForceUnits) / FMath::Max(Mass, KINDA_SMALL_NUMBER);<br> <br> if (Accumulator &lt; TotalTime)<br> {  <br>  Position += Velocity * DeltaTime;<br>  Velocity += Acceleration * DeltaTime;<br>  <br>  TickCount++;<br>  Accumulator += DeltaTime;<br> }<br> else<br> {<br>  if (!Stop)<br>  {<br>   double ElapsedTime = FPlatformTime::Seconds() - StartTime;<br>   <br>   UE_LOG(LogTemp, Type::Display, TEXT(&quot;Explicit Euler -- TickCount = %d\tAccumulator = %f\tPosition = (%f, %f, %f)\tVelocity = (%f, %f, %f)&quot;),<br>    TickCount, Accumulator, Position.X, Position.Y, Position.Z, Velocity.X, Velocity.Y, Velocity.Z);<br><br>   UE_LOG(LogTemp, Type::Display, TEXT(&quot;Explicit Euler -- Elapsed Unreal Time = %f\t&quot;), GetWorld()-&gt;GetTimeSeconds());<br>   UE_LOG(LogTemp, Type::Display, TEXT(&quot;Explicit Euler -- Elapsed Real Time = %f\t&quot;), ElapsedTime);<br>    <br>   Stop = true;<br>  }<br> }<br><br> SetActorLocation(Position); <br>}</pre><p>Set the object’s mass to 1 kg, place it at the origin (0, 0, 0), and apply a constant force of 10 N.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*U5lU0e1yb2arskIca8UR1A.png" /></figure><p>For the first simulation, we’ll use a fixed frame rate of <strong>15 FPS</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ePiG0nM_VeEmcv42f4qnxg.png" /></figure><p>After running the simulation, we observe that after 10.06 seconds (slightly more than 10, due to an extra iteration right after the limit), the cube has traveled 503.33 meters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GtlHYPKZG5uX7sJibtcuhg.gif" /><figcaption>Cube simulated with the explicit Euler method to model linear motion at 15 fps</figcaption></figure><p>Using the classic equation for uniformly accelerated motion we can calculate how it should have traveled:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/156/1*MO5mDYqmwYKtsf9G9UvUOw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*ERoR9qVG1tdc-3-zAd_Nsg.png" /></figure><p>The simulation result is slightly underestimated.</p><p>The error is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*z2G_AIKG4D-K6_9EDX_3EA.png" /></figure><p><strong>Can we do better?</strong></p><p>Yes — the smaller the time step, the more accurate Euler’s approximation becomes.</p><p>Let’s try again with a fixed frame rate of <strong>150 FPS</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RlY_Sb2gvPjy9sS1BtGCFA.gif" /><figcaption>Cube simulated with the explicit Euler method to model linear motion at 150 fps</figcaption></figure><p>Now, after 10.00 seconds, the cube travels 499.66 meters.</p><p>Again, using the classic equation for uniformly accelerated motion we can calculate how it should have traveled, and how large the error is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*G2YbhAfgJehbOHcV1_F0sA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*YMs51i1t1sQUY69SqQbDXA.png" /></figure><p>It should have traveled 500.01 meters, resulting in a 0.06% error — <strong>much smaller!</strong></p><p>Even though my system never actually reached 150 FPS (it stabilized around 90 FPS), the result remains correct, despite the simulation taking about 16 seconds instead of 10.</p><p>Why? Because Unreal still uses the fixed delta time for calculations.</p><p>This behavior is called <strong><em>deterministic</em></strong>, meaning you’ll get the same result on any hardware, as long as the input and delta time are the same.</p><h4><strong>Spring-Damper System and Oscillations</strong></h4><p>Now let’s explore a more complex scenario: a spring-damper system.</p><p>Here, a mass is attached to a spring.</p><p>When the spring is stretched and released, it begins to oscillate (harmonic motion), and is gradually slowed down by a damping force that resists its movement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/0*xbM4nAWKJxgGGNdZ.gif" /></figure><p>Acceleration is no longer constant — it changes both in magnitude and direction.</p><p>This system is modeled using Hooke’s law with damping:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/215/1*7pm5g5mqvD7jkKukkd5dtg.png" /></figure><p>· k is the spring constant</p><p>· x is the displacement from rest</p><p>· c is the damping coefficient (higher = more resistance)</p><p>· v is the velocity of the mass</p><p>We build an actor using the same explicit Euler integration, calculating motion in the <em>tick </em>method.</p><pre>UCLASS()<br>class PHYSICSPLAYGROUND_API AHarmonicExplicitEulerTick : public AActor<br>{<br> GENERATED_BODY()<br><br>public:<br> UPROPERTY(EditAnywhere)<br> float Mass;<br> UPROPERTY(EditAnywhere)<br> float K;<br> UPROPERTY(EditAnywhere)<br> float Damper;<br><br> UPROPERTY(EditAnywhere)<br> TObjectPtr&lt;UStaticMeshComponent&gt; StaticMesh;<br> <br>public:<br> AHarmonicExplicitEulerTick();<br> virtual void Tick(float DeltaTime) override;<br><br>protected:<br> virtual void BeginPlay() override;<br><br>private:<br> FVector StartLocation;<br> FVector Position;<br> FVector Velocity;<br> <br> int32 TickCount;<br>};</pre><pre>AHarmonicExplicitEulerTick::AHarmonicExplicitEulerTick()<br>{<br> PrimaryActorTick.bCanEverTick = true;<br><br> StaticMesh = CreateDefaultSubobject&lt;UStaticMeshComponent&gt;(&quot;StaticMesh&quot;);<br> StaticMesh-&gt;SetupAttachment(RootComponent);<br>}<br><br>void AHarmonicExplicitEulerTick::BeginPlay()<br>{<br> Super::BeginPlay();<br> <br> StaticMesh-&gt;SetSimulatePhysics(false);<br><br> TickCount = 0;<br> StartLocation = FVector(0, GetActorLocation().Y, GetActorLocation().Z);<br> Position = GetActorLocation();<br> Velocity = FVector::ZeroVector;<br>}<br><br>void AHarmonicExplicitEulerTick::Tick(float DeltaTime)<br>{<br> Super::Tick(DeltaTime);<br><br> TickCount++;<br> <br> const FVector DistanceFromStart = GetActorLocation() - StartLocation;<br> const FVector Force = -DistanceFromStart * K - Velocity * Damper;<br> const FVector Acceleration = Force / FMath::Max(Mass, KINDA_SMALL_NUMBER);<br><br> Position += Velocity * DeltaTime;<br> Velocity += Acceleration * DeltaTime;<br><br> SetActorLocation(Position);<br>}</pre><p>Let’s set a fixed frame rate of <strong>90 FPS.</strong></p><p>Immediately, we see something odd — <strong>the mass does not decelerate or settle</strong>.</p><p>At <strong>30 FPS</strong>, things get worse: <strong>the system doesn’t stabilize</strong> but instead amplifies the oscillations infinitely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b8PHauEQ8sKaxzSHB9U5YA.gif" /><figcaption>Cube simulated with the explicit Euler method to model harmonic motion</figcaption></figure><p>This demonstrates that the <strong>explicit Euler</strong> method not only <strong>requires a very small time step to work correctly</strong>, but it also <strong>gives inaccurate results</strong> when the <strong>acceleration is not constant</strong>.</p><p>We need something better…</p><h4><strong>Enter Semi-Implicit Euler</strong></h4><p>In our current method, the new position is calculated using the previous velocity.</p><p>In systems with high acceleration, this causes delays in position updates.</p><p>Let’s modify our integration step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*QHYzFH4JBogrc8pFyaY0Gg.png" /></figure><p>This is called <strong><em>semi-implicit Euler</em></strong>.</p><p>It updates the position using the newly computed velocity, not the old one.</p><p>Semi-implicit Euler comes from the study of <strong><em>Hamiltonian </em></strong>systems, where total energy is conserved (e.g., an ideal spring).</p><p>Explicit Euler doesn’t preserve energy — it often adds energy, causing simulations to “explode”.</p><p>Semi-implicit Euler doesn’t exactly conserve energy, but it oscillates around the correct value, maintaining long-term stability. This property is called symplectic stability.</p><p>Let’s apply this small change to our code and compare results.</p><pre>AHarmonicSemiImplicitEulerTick::AHarmonicSemiImplicitEulerTick()<br>{<br> PrimaryActorTick.bCanEverTick = true;<br><br> StaticMesh = CreateDefaultSubobject&lt;UStaticMeshComponent&gt;(&quot;StaticMesh&quot;);<br> StaticMesh-&gt;SetupAttachment(RootComponent);<br>}<br><br>void AHarmonicSemiImplicitEulerTick::BeginPlay()<br>{<br> Super::BeginPlay();<br><br> StaticMesh-&gt;SetSimulatePhysics(false);<br><br> TickCount = 0;<br> StartLocation = FVector(0, GetActorLocation().Y, GetActorLocation().Z);<br> Position = GetActorLocation();<br> Velocity = FVector::ZeroVector;<br>}<br><br>void AHarmonicSemiImplicitEulerTick::Tick(float DeltaTime)<br>{<br> Super::Tick(DeltaTime);<br><br> TickCount++;<br> <br> const FVector DistanceFromStart = GetActorLocation() - StartLocation;<br> const FVector Force = -DistanceFromStart * K - Velocity * Damper;<br> const FVector Acceleration = Force / FMath::Max(Mass, KINDA_SMALL_NUMBER);<br><br> Velocity += Acceleration * DeltaTime;<br> Position += Velocity * DeltaTime;<br><br> SetActorLocation(Position);<br>}</pre><p>Even at very low frame rates (<strong>15 FPS</strong>), the system now converges to its rest position!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PLKMCmqP1Cdz343shJA9xg.gif" /><figcaption>At 60 FPS, the green cube, using the explicit Euler integrator, fails to stabilize and accumulates energy, resulting in increasing oscillations. In contrast, the blue cube, using the semi-implicit Euler integrator, yields a more realistic behavior by damping the oscillations and eventually stabilizing.</figcaption></figure><p>Let’s also compare the two integrators in the previous uniformly accelerated motion simulation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WUz1P1GOAozbHn01lgkl3g.gif" /><figcaption>The green cube is simulated using the explicit Euler integrator; the blue cube uses the semi-implicit Euler integrator.</figcaption></figure><p>We notice that the semi-implicit method slightly overestimates the result compared to the explicit one, while still maintaining the same level of accuracy even at low frame rates.</p><h4><strong>Unreal’s Built-In Integrator</strong></h4><p>Modern game engines — Unreal included — use an integrator very similar to semi-implicit Euler.</p><p>To verify this, we build an actor that moves its mesh using Unreal’s built-in physics.</p><p>We only apply the AddForce in the <em>tick </em>function, and let Unreal handle the rest.</p><pre>UCLASS()<br>class PHYSICSPLAYGROUND_API AUnrealSolver : public AActor<br>{<br> GENERATED_BODY()<br><br>public:<br> UPROPERTY(EditAnywhere)<br> FVector Force;<br> UPROPERTY(EditAnywhere)<br> float Mass;<br> UPROPERTY(EditAnywhere)<br> float TotalTime;<br> UPROPERTY(VisibleAnywhere)<br> float Accumulator;<br><br> UPROPERTY(EditAnywhere)<br> TObjectPtr&lt;UStaticMeshComponent&gt; StaticMesh;<br><br>public:<br> AUnrealSolver();<br> virtual void Tick(float DeltaTime) override;<br><br>protected:<br> virtual void BeginPlay() override;<br><br>private:<br> const float ToUnrealForceUnits = 100.0f;<br> <br> FVector Position;<br> FVector Velocity;<br><br> int32 TickCount;<br>};</pre><pre>AUnrealSolver::AUnrealSolver()<br>{<br> PrimaryActorTick.bCanEverTick = true;<br><br> StaticMesh = CreateDefaultSubobject&lt;UStaticMeshComponent&gt;(&quot;StaticMesh&quot;);<br> StaticMesh-&gt;SetupAttachment(RootComponent);<br>}<br><br>void AUnrealSolver::BeginPlay()<br>{<br> Super::BeginPlay();<br><br> TickCount = 0;<br> Accumulator = 0.0f;<br> StaticMesh-&gt;SetMassOverrideInKg(NAME_None, Mass);<br> StaticMesh-&gt;SetLinearDamping(0.0f);<br> StaticMesh-&gt;SetAngularDamping(0.0f);<br> StaticMesh-&gt;SetSimulatePhysics(true);<br>}<br><br>void AUnrealSolver::Tick(float DeltaTime)<br>{<br> Super::Tick(DeltaTime);<br> <br> if (StaticMesh-&gt;IsSimulatingPhysics())<br> {<br>  Position = GetActorLocation();<br>  Velocity = StaticMesh-&gt;GetComponentVelocity();<br>  <br>  if (Accumulator &lt; TotalTime)<br>  {<br>   StaticMesh-&gt;AddForce(Force * ToUnrealForceUnits);<br><br>   TickCount++;<br>   Accumulator += DeltaTime;<br>  }<br>  else<br>  {<br>   UE_LOG(LogTemp, Type::Display, TEXT(&quot;Unreal Solver -- TickCount = %d\tPosition = (%f, %f, %f)\tVelocity = (%f, %f, %f)&quot;),<br>    TickCount, Position.X, Position.Y, Position.Z, Velocity.X, Velocity.Y, Velocity.Z);<br><br>   StaticMesh-&gt;SetSimulatePhysics(false);<br>  }<br> }<br>}</pre><p>Comparing this to our two custom integrators, the results — at both low (<strong>30 FPS</strong>) and high (<strong>100 FPS</strong>) frame rates — match the semi-implicit method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kYxJT7i5dP_32GZXTqo01Q.gif" /><figcaption>The green cube is simulated using the explicit Euler integrator, the blue cube with the semi-implicit Euler integrator, and the red cube with the Unreal solver</figcaption></figure><p>To summarize, <strong>semi-implicit Euler</strong> is the <strong>best trade-off between precision, performance and stability</strong>, and is one of the most widely used methods in commercial game engines.</p><h4><strong>Substepping and Precision</strong></h4><p>Historically, in Unreal Engine, the physics step was <strong>tightly coupled</strong> to the main game tick.</p><p>This meant physics updates happened once per frame, using the game tick’s delta time — reducing precision if the frame rate dropped.</p><p>To fix this, Unreal introduced <strong><em>substepping</em></strong>.</p><p>With substepping, Unreal internally splits the tick’s delta time into smaller steps, and updates physics at each substep.</p><p>This makes it possible to lower the game frame rate without losing physics accuracy, while still keeping physics and gameplay logic in sync.</p><p>Substepping settings can be found in the “<strong><em>Project Settings” </em></strong>under “<strong><em>Engine” </em></strong>→ “<strong><em>Physics”</em></strong>.</p><p>To enable it:</p><p>· Check “<strong><em>Substepping</em></strong>”</p><p>· Set “<strong><em>Max Substep Delta Time</em>”</strong> (max duration for each substep)</p><p>· Set “<strong><em>Max Substeps</em></strong>” (max iterations per frame)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V7evlnatDW54qHB9HO5HZA.png" /></figure><p>For example, with these parameters: if the tick delta time exceeds 10ms (as the frame rate drops below 100 FPS), Unreal splits the physics frame into smaller substeps.</p><p>If even the max substeps aren’t enough, Unreal will stretch the substep duration — reducing precision.</p><p>We can simulate this ourselves.</p><p>Let’s build an actor affected by gravity, using semi-implicit integration and a custom substepping loop inside tick.</p><p>Our substepping logic approximates Unreal’s, though the real implementation is more advanced.</p><pre>UCLASS()<br>class PHYSICSPLAYGROUND_API ASubstepBouncingBall : public AActor<br>{<br> GENERATED_BODY()<br><br>public:<br> UPROPERTY(EditAnywhere)<br> float Mass;<br> UPROPERTY(EditAnywhere)<br> float Gravity;<br> UPROPERTY(EditAnywhere)<br> float Restitution;<br> UPROPERTY(EditAnywhere)<br> float GroundHeight = 0.0f;<br><br> UPROPERTY(EditAnywhere)<br> bool Substepping;<br> UPROPERTY(EditAnywhere, meta = (EditCondition = &quot;Substepping&quot;))<br> float MaxDt;<br> UPROPERTY(EditAnywhere, meta = (EditCondition = &quot;Substepping&quot;))<br> float MaxSubsteps;<br> <br> UPROPERTY(EditAnywhere)<br> TObjectPtr&lt;UStaticMeshComponent&gt; StaticMesh;<br><br>public:<br> ASubstepBouncingBall();<br> virtual void Tick(float DeltaTime) override;<br><br>protected:<br> virtual void BeginPlay() override;<br><br>private:<br> const float ToUnrealForceUnits = 100.0f;<br> <br> FVector Position;<br> FVector Velocity;<br><br> int32 PhysicsTickCount;<br><br>private:<br> void PhysicsComputation(float Dt);<br>};</pre><pre>ASubstepBouncingBall::ASubstepBouncingBall()<br>{<br> PrimaryActorTick.bCanEverTick = true;<br><br> StaticMesh = CreateDefaultSubobject&lt;UStaticMeshComponent&gt;(&quot;StaticMesh&quot;);<br> StaticMesh-&gt;SetupAttachment(RootComponent);<br>}<br><br>void ASubstepBouncingBall::BeginPlay()<br>{<br> Super::BeginPlay();<br><br> StaticMesh-&gt;SetSimulatePhysics(false);<br><br> PhysicsTickCount = 0;<br> <br> Position = GetActorLocation();<br> Velocity = FVector::ZeroVector;<br>}<br><br>void ASubstepBouncingBall::Tick(float DeltaTime)<br>{<br> Super::Tick(DeltaTime);<br><br> if (Substepping)<br> {<br>  int32 SubstepsCount = FMath::CeilToInt32(DeltaTime / MaxDt);<br>  if (SubstepsCount &gt; MaxSubsteps)<br>   SubstepsCount = MaxSubsteps;<br><br>  float SubstepTime = DeltaTime / SubstepsCount;<br>  if (SubstepTime &gt; MaxDt)<br>   SubstepTime = MaxDt;<br><br>  for (int32 i = 0; i &lt; SubstepsCount; ++i)<br>  {<br>   PhysicsComputation(SubstepTime);<br>  }<br> }<br> else<br> {<br>  PhysicsComputation(DeltaTime);<br> }<br> <br> SetActorLocation(Position);<br>}<br><br>void ASubstepBouncingBall::PhysicsComputation(float Dt)<br>{<br> PhysicsTickCount++;<br> <br> Velocity.Z += Gravity * Dt;<br> Position += Velocity * Dt;<br><br> if (Position.Z &lt;= GroundHeight)<br> {<br>  Position.Z = GroundHeight;<br>  Velocity.Z *= -Restitution;<br><br>  if (FMath::Abs(Velocity.Z) &lt; 10.0f)<br>  {<br>   Velocity.Z = 0.0f;<br>  }<br> }<br>}</pre><p>If we simulate at a problematic <strong>15 FPS</strong>, the ball using substeps of 0.01 continues to bounce correctly, while the non-substepped one loses accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*e6DQeFKDPVRWO8hNEnZwaw.gif" /><figcaption>The red ball uses substepping, while the green ball does not</figcaption></figure><p>This technique lets us decouple physics frequency from game tick rate, without drawbacks.</p><h4><strong>Chaos and Async Physics Tick</strong></h4><p>Starting with Unreal Engine 5.0, <em>PhysX</em> is no longer the default physics engine.</p><p>Instead, Epic introduced <strong><em>Chaos</em></strong>, its own in-house physics system.</p><p>One major improvement is the ability to run <strong>physics </strong>on a <strong>separate thread</strong>, using the <strong><em>Async Physics Tick</em></strong>.</p><p>The physics simulation now runs in a parallel physics thread, which:</p><p>· Can guarantee a fixed time step with constant delta time</p><p>· Can run at a different frequency from the game tick</p><p>· Communicates with the game thread through synchronized buffers</p><p>This means that the <strong>game and physics threads are no longer updated in real-time sync</strong>.</p><p>This setup may sound familiar to <strong><em>Unity</em></strong> developers, since <em>Unity</em> has always used a fixed-step physics system, separating game logic (in <em>Update() </em>method) from physics logic (in <em>FixedUpdate()</em> method).</p><p>Now, let’s verify whether the physical state information of a body instance, when read from the game tick, actually differs from the one computed on the physics thread.</p><p>To do this, we’ll use the <strong><em>Async Tick Physics</em></strong> plugin, available for free on <strong><em>GitHub (</em></strong><a href="https://github.com/Mr-Craig/AsyncTickPhysics">https://github.com/Mr-Craig/AsyncTickPhysics</a>).</p><p>This plugin greatly simplifies interacting with the physics thread in Blueprints.</p><p>Using it is quite straightforward:</p><p>· Enable the plugin</p><p>· Activate “<strong>Tick Physics Async”</strong> from Unreal’s “<strong><em>Physics Settings</em></strong>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZIqvFag91v6cQVvNapEGhg.png" /></figure><p>· Create a new Blueprint and derive your Pawn from the <em>AsyncTickPawn </em>class</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*nqyP3w_gZzdsA75LYfgNhg.png" /></figure><p>· Create two variables to store position vectors — this is essential because we cannot access non-thread-safe operations (like printing to the screen or log) directly from the physics thread. We’ll instead store the values and print them later in the main tick function, when it’s safe to do so</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*hzL03sb5o7p5u5XQqoICzg.png" /></figure><p>· In the <em>AsyncTick event</em>, use the plugin to retrieve the transform of the physical object</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EaANf60hQmXkb7X9BQQ_ZQ.png" /></figure><p>· In the regular tick function, retrieve the transform using the classic <em>GetWorldLocation</em> node and compare the two vectors, printing the results</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RbB0VEoLuhqLj-kCxbWb0w.png" /></figure><p>Running the simulation reveals a significant difference between the transform read from the physics thread and the one retrieved during the game tick.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*n_XaiPzZvQuRHqvc9O7WAA.gif" /></figure><p>This demonstrates that when <em>Async Physics</em> is enabled, developers need to be careful about how they read or apply physical state values.</p><p>Readings from the game thread (such as <em>GetActorLocation</em> or <em>GetComponentTransform</em>) may be interpolated or outdated compared to the actual physical state.</p><h4><strong>Conclusion</strong></h4><p>In this article, we explored Unreal Engine’s physics system — from <strong><em>numerical integration</em></strong> and <strong><em>substepping</em></strong>, to the new <strong><em>asynchronous physics tick</em></strong>. Understanding these mechanisms is essential for building stable and performant simulations.</p><p><strong>Thanks for reading!</strong></p><p>If you found it helpful, don’t forget to like, subscribe, and leave a comment with your thoughts or questions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ac7bc9ee5fb" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/tick-by-tick-how-unreal-engine-simulates-real-world-physics-4ac7bc9ee5fb">Tick by Tick: How Unreal Engine Simulates Real-World Physics</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unleashing Massive Flocks with Unity]]></title>
            <link>https://levelup.gitconnected.com/unleashing-massive-flocks-with-unity-30ef13aea78b?source=rss-fe9a23aaa782------2</link>
            <guid isPermaLink="false">https://medium.com/p/30ef13aea78b</guid>
            <category><![CDATA[flocking]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[boid]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[unity-game-development]]></category>
            <dc:creator><![CDATA[Federico Grenoville]]></dc:creator>
            <pubDate>Fri, 06 Jun 2025 03:32:50 GMT</pubDate>
            <atom:updated>2025-06-06T03:32:50.987Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yd5OWdoHOmrTcnJ5C1Gq5A.png" /></figure><h4><strong>1. Introduction</strong></h4><p>In 1986, Craig Reynolds introduced a surprisingly simple yet powerful computational model to simulate the collective behavior of bird flocks. He called it <em>Boids</em>, a stylized abbreviation of <em>Bird-oid objects</em>.</p><p>The idea was as elegant as it was revolutionary: complex group behavior can emerge from a few simple local rules. You don’t need centralized intelligence to coordinate a flock of birds, a school of fish, or a crowd of people, just a handful of rules, applied by each <em>agent</em> (which we’ll also call <em>boids</em> or <em>entities</em>) in response to its immediate neighbors.</p><p>Reynolds defined three core behaviors:</p><ul><li><strong>Alignment</strong> — steer toward the nearby agents’ average heading</li><li><strong>Cohesion</strong> — move toward nearby agents’ center of mass</li><li><strong>Separation</strong> — avoid crowding neighbors by maintaining a minimum distance.</li></ul><p>By applying these rules at every frame for every agent, the simulation quickly generates realistic dynamics: fluid waves of motion, natural obstacle avoidance, self-organization, none of which are explicitly programmed but rather emerge from local interactions.</p><h4><strong>2. How Boids work</strong></h4><p>At the heart of the <em>Boids</em> algorithm are three fundamental rules. Each act on an individual level, but when applied together across a population of <em>agents</em>, they produce surprisingly lifelike group behavior.</p><ul><li><strong>Alignment</strong><br> <em>“Match the average heading of your neighbors”.</em><br> Each <em>entity</em> looks at the direction of its nearest neighbors (within a certain range) and slightly adjusts its heading to align with the average.<br> Think of it like walking in a group and unconsciously syncing your pace with the others.<br> This helps create the illusion of a unified organism with a shared direction.</li><li><strong>Cohesion</strong><br> <em>“Move toward the center of your neighbors”.</em><br> Each <em>entity</em> tries not to fall too far behind or stray from the group. It calculates the center of mass (centroid) of its neighbors and moves slightly toward it.<br> This keeps the group from scattering too far without making it clump unnaturally.</li><li><strong>Separation</strong><br> <em>“Don’t get too close”.</em><br> If an <em>agent</em> gets too close to another, it steers away to avoid collisions. This is perhaps the most intuitive: nobody wants to bump into others.<br> This rule maintains safe spacing between <em>agents</em>, preventing the flock from collapsing into a single blob.</li></ul><p>On their own, these rules don’t accomplish much. But together, they produce compelling emergent behavior:</p><ul><li>The flock changes direction like a fluid wave.</li><li><em>Agents</em> split and regroup naturally.</li><li>They can dodge obstacles or respond to predators, if implemented.</li></ul><p>All this happens <strong>without</strong> a centralized <em>flock manager</em>. The behavior emerges from the bottom up.</p><h4><strong>3. Extra features: predators, explosions, and real-time interaction</strong></h4><p>What makes this kind of simulation truly captivating is its ability to react to the environment, generate chaos, and then return to balance. Here are some interactive dynamics I added to the simulation:</p><ul><li><strong>Predators: </strong>to make the behavior more believable (and fun), I added <em>predators</em>. These special <em>agents</em> move independently or chase nearby <em>entities, </em>trigger an escape response within a certain radius, are perceived by <em>agents</em> as a repulsive force (an “anti-cohesion”).</li></ul><p>When a <em>predator</em> enters the flock, <em>boids</em> fan out, holes appear in the swarm, or subgroups form, all without scripting the choreography. It happens organically.</p><ul><li><strong>Click-triggered explosions: </strong>you can create a repulsive force by double-clicking the left mouse button.<br> All <em>boids</em> within a certain radius quickly flee the explosion point, then gradually return to normal, re-forming the swarm.</li><li><strong>Click-and-hold attraction: </strong>this works opposite to the explosion.<br> When holding the <strong>right mouse button</strong>, an attractive force pulls <em>boids</em> within a defined radius toward the cursor.<br> As you move the mouse, you can drag clusters of <em>boids</em> around the scene.</li></ul><p>All of this makes the simulation interactive and even playful, just disrupting the flock and watching how it reacts is satisfying.</p><p>At this point, the swarm is no longer just a coherent blob, it’s a <strong>dynamic ecosystem</strong>, where:</p><ul><li>the group forms, breaks, and recomposes</li><li>it reacts to threats and reorganizes after shocks</li><li>you can observe animal-like behavior, even though none of it was explicitly programmed.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FN55d8byORAs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DN55d8byORAs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FN55d8byORAs%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9908de388b1439dc1f2c77ac4236852/href">https://medium.com/media/d9908de388b1439dc1f2c77ac4236852/href</a></iframe><h4><strong>4. The Scalability Challenge</strong></h4><p>The <em>Boids</em> rules, taken individually, are simple and cheap to compute. But when theory meets practice, a key issue arises: <strong>scalability</strong>.</p><p><strong>The neighbor search problem<br></strong>Each <em>agent</em> needs to find out who its neighbors are, meaning that every frame, each <em>agent</em> must compare itself with all others to determine proximity. This happens for <strong>every</strong> <em>agent</em>, on <strong>every</strong> update.</p><p>From a computational perspective, this means <strong>O(n²)</strong> complexity:</p><ul><li>100 boids → 10,000 comparisons.</li><li>1,000 boids → 1 million.</li><li>10,000 boids → 100 million!</li></ul><p>Even with modern hardware, this quickly becomes unsustainable. The result? A laggy, unmanageable simulation.</p><p>To scale the simulation to thousands of agents, we need optimizations:</p><p>· Reduce the number of comparisons by organizing spatial data more efficiently, this is where spatial structures like the <strong>QuadTree</strong> come in.</p><p>· Use modern multi-core CPUs to parallelize the rule calculations.</p><h4><strong>5. Optimizing spatial partitioning (<em>QuadTree</em>)</strong></h4><p>A <strong><em>QuadTree</em></strong> is a hierarchical data structure that recursively subdivides a 2D space into four quadrants.</p><p>Imagine having a map and dividing it into four smaller rectangles. If one contains too much “stuff” (in our case, too many <em>boids</em>), you subdivide it again, and so on.</p><p>This creates a tree-like spatial structure, where each node represents a region, and its children represent sub-regions.</p><p>I implemented a <em>QuadTree</em> in Unity, visualizing the defined regions. I set a limit of 3 entities per region. Once that limit is exceeded, the region is subdivided further.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oAjBMhS6_wiuhogDFUwsXg.gif" /></figure><p><strong>How does this help?<br></strong>Instead of comparing every boid to every other:</p><ol><li>We build the <em>QuadTree</em>, placing each agent in the appropriate region.</li><li>To find an <em>agent</em>’s neighbors, we query only the region it’s in and adjacent regions, within a defined radius.</li></ol><p>Let’s look at the diagram below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aXsW7jy7AYegnbv1kBW35Q.png" /></figure><p>The agent in region <em>A</em> wants to find neighbors within the green circle.<br> Since the circle overlaps regions <em>A</em> and <em>D</em>, we only search those two, skipping all others.<br> This drastically reduces the number of comparisons.</p><p>In well-distributed scenarios, this can bring the complexity down to <strong>O(n log n)</strong>.</p><p><strong>Implementation in Unity<br></strong>I created a QuadTree class and a NodeTree class.</p><ul><li>QuadTree handles tree construction, using NodeTree objects as its data structure.</li><li>NodeTree manages spatial partitioning and entity insertion.</li></ul><p>There are two main variants of a <em>QuadTree</em>:</p><ol><li><strong><em>Point (or Loose) QuadTree</em></strong> — when a node exceeds its capacity, all points are redistributed into its children.</li><li><strong><em>Bucket (or Cell) QuadTree</em></strong> — when a node exceeds capacity, it is subdivided, but the points are not redistributed up the tree; each level handles only its own inserts.</li></ol><p>I implemented both for comparison. In our simulation, performance is nearly identical for either version, so I’m sticking with the <em>Bucket</em> one.</p><pre>public class QuadTree : MonoBehaviour<br>{<br>  [SerializeField] private int _nodeCapacity;<br>  [SerializeField] private Rect _bounds;<br>  [SerializeField] private float _nodeMinSize;<br>  <br>  public int NodeCapacity =&gt; _nodeCapacity;<br>  public Rect Bounds =&gt; _bounds;<br>  public float NodeMinSize =&gt; _nodeMinSize;<br>  <br>  private NodeTree _root;<br>  <br>  public void Build(NativeArray&lt;float2&gt; boidPositions)<br>  {<br>    int boidCount = boidPositions.Length;<br>      <br>    _root = new NodeTree(_bounds, _nodeCapacity, _nodeMinSize, 0);<br>  <br>    for (int i = 0; i &lt; boidCount; i++)<br>        _root.Insert(i, boidPositions[i]);<br>  }<br><br>  public void QueryRange(Rect range, NativeArray&lt;float2&gt; boidPositions, NativeList&lt;int&gt; found)<br>  {<br>      _root.QueryRange(range, boidPositions, found);<br>  }<br>}<br><br>public class NodeTree<br>{<br>  public Rect Bounds =&gt; _bounds;<br>  public NodeTree[] Children =&gt; _children;<br>  public bool IsDivided =&gt; _isDivided;<br>  <br>  private Rect _bounds;<br>  private readonly List&lt;int&gt; _points;<br>  private NodeTree[] _children;<br>  private readonly int _nodeCapacity;<br>  private readonly float _nodeMinSize;<br>  private bool _isDivided;<br>  private readonly int _nodeDepth;<br>  <br>  public NodeTree(Rect bounds, int nodeCapacity, float nodeMinSize, int depth)<br>  {<br>      _bounds = bounds;<br>      _nodeCapacity = nodeCapacity;<br>      _nodeMinSize = nodeMinSize;<br>      _nodeDepth = depth;<br>      _isDivided = false;<br>      _points = new List&lt;int&gt;();<br>  }<br>  <br>  public void Subdivide()<br>  {<br>      Vector2 halfBound = new Vector2(_bounds.width, _bounds.height) / 2;<br><br>      Rect nw = new Rect(new Vector2(_bounds.x, _bounds.y + halfBound.y), halfBound);<br>      Rect ne = new Rect(new Vector2(_bounds.x + halfBound.x, _bounds.y + halfBound.y), halfBound);<br>      Rect sw = new Rect(new Vector2(_bounds.x, _bounds.y), halfBound);<br>      Rect se = new Rect(new Vector2(_bounds.x + halfBound.x, _bounds.y), halfBound);<br>      <br>      _children = new NodeTree[4];<br>      _children[0] = new NodeTree(nw, _nodeCapacity, _nodeMinSize, _nodeDepth + 1);<br>      _children[1] = new NodeTree(ne, _nodeCapacity, _nodeMinSize, _nodeDepth + 1);<br>      _children[2] = new NodeTree(sw, _nodeCapacity, _nodeMinSize, _nodeDepth + 1);<br>      _children[3] = new NodeTree(se, _nodeCapacity, _nodeMinSize, _nodeDepth + 1);<br><br>      _isDivided = true;<br>  }<br>  <br>  /*<br>   *  Bucket Quadtree (also known as Cell Quadtree)<br>   */<br>  public bool Insert(int index, float2 point)<br>  {<br>      if (!_bounds.Contains(new Vector2(point.x, point.y)))<br>          return false;<br>      <br>      if (_points.Count &lt; _nodeCapacity || !CanDivide())<br>      {<br>          _points.Add(index);<br>          return true;<br>      }<br>      else <br>      {<br>          if (!_isDivided)<br>              Subdivide();<br>  <br>          foreach (var child in _children)<br>          {<br>              if (child.Insert(index, point))<br>                  return true;<br>          }<br>      }<br>      return false;<br>  }<br>  <br>  private bool CanDivide()<br>  {<br>      return (_bounds.width &gt;= _nodeMinSize &amp;&amp; _bounds.height &gt;= _nodeMinSize);<br>  }<br><br>  public void QueryRange(Rect range, NativeArray&lt;float2&gt; boidPositions, NativeList&lt;int&gt; found)<br>  {<br>      if (!_bounds.Overlaps(range, true))<br>          return;<br><br>      foreach (var p in _points)<br>      {<br>          if (range.Contains(boidPositions[p]))<br>          {<br>              found.Add(p);<br>          }<br>      }<br><br>      if (_isDivided)<br>      {<br>          foreach (var child in _children)<br>          {<br>              child.QueryRange(range, boidPositions, found);<br>          }<br>      }<br>  }<br>}<br></pre><p><strong>Trade-offs and Limits</strong></p><ul><li><strong>High density reduces efficiency:</strong> if many <em>boids</em> are crammed into a small area, comparisons can still approach <strong>O(n²)</strong>.</li><li><strong>Tree must be rebuilt every frame:</strong> since <em>boids</em> can move fast, region assignments change constantly. In theory, we could update instead of rebuild, but it would be complex and computationally expensive, so I prefer to rebuild the <em>QuadTree</em> every frame.</li><li><strong>Build cost exists</strong>, but is <strong>outweighed by the performance gains</strong> in neighbor searches.</li></ul><h4><strong>6. Optimizing with Unity Jobs &amp; Burst Compiler</strong></h4><p>After optimizing the neighbor search with <em>QuadTree</em>, another bottleneck remains: the <strong>per-frame computation</strong> each entity must perform.</p><p>Even with fast lookups, each <em>agent</em> still has to:</p><ul><li>compute forces based on neighbors,</li><li>update its position and velocity,</li><li>avoid obstacles, predators, explosions, etc.</li></ul><p>By default, Unity runs all this on the <strong>main thread</strong>, sequentially. This wastes the potential of multi-core CPUs.</p><p>The <strong>Job System</strong> is Unity’s way to let developers write safe, multithreaded code.<br> It allows us to break tasks into “jobs” that run in parallel across CPU cores, perfect for operations repeated across many data points.</p><p>But parallel programming comes with trade-offs:</p><ol><li><strong>Limited Unity API access:</strong> jobs can’t access Transform, GameObject, or other non-thread-safe components.</li><li><strong>Only blittable types:</strong> jobs must use blittable data types (bool, int, float, native array). Blittable data<strong> </strong>refers to data types that have the same binary representation in managed and unmanaged memory. This means they can be directly copied from one memory space to another without transformation or marshaling.</li><li><strong>Manual memory management:</strong> with NativeArray and similar structures, developers must allocate and deallocate memory manually.</li><li><strong>Setup overhead:</strong> preparing and synchronizing jobs adds complexity, so it’s best suited for heavy, repetitive workloads.</li></ol><p>In combination with the Job System, Unity’s <strong>Burst Compiler</strong> can compile your code into highly optimized machine instructions, squeezing out even more performance.</p><p><strong>How I used jobs in my simulation<br></strong>First, I identified which logic could be parallelized:<br>Parallelizable:</p><ul><li>The behaviors of agents: Alignment, Separation, Cohesion, Attraction, Repulsion, Flee, Wander</li></ul><p>Not parallelizable:</p><ul><li><em>QuadTree</em> construction and search (due to data structure complexity).</li></ul><p>Second, for each entity, I determined the maximum neighbor distance of interest, then I built three arrays:</p><ul><li>neighborsArray: a flat map of neighbors.</li><li>neighborsCounts: how many neighbors each agent has.</li><li>neighborsStartIndices: where each agent’s neighbors begin in the flat array.</li></ul><p>This setup let me <strong>pass read-only data to jobs</strong>, which is ideal for safe parallelism.</p><p><em>Note: below is a stripped-down excerpt of the </em><em>Update() method, focused solely on the part where neighbor arrays (</em><em>_neighborsArray, </em><em>_neighborsCounts, </em><em>_neighborsStartIndices) are built.<br> The actual job scheduling and execution logic that follows has been omitted here for clarity and focus.</em></p><pre>void Update()<br>{<br>  _quadTree.Build(_boids.Positions);<br><br>  int neighborIdx = 0;<br>  for (int i = 0; i &lt; _boids.Count; i++)<br>  {<br>      _neighborsStartIndices[i] = neighborIdx;<br>      _neighborsCounts[i] = 0;<br><br>      NativeList&lt;int&gt; foundNeighbors = new NativeList&lt;int&gt;(Allocator.Temp);<br>      <br>      Vector2 halfPos = new Vector2(_boids.Positions[i].x - _boids.MaxPerceptionRadius/2,<br>          _boids.Positions[i].y - _boids.MaxPerceptionRadius/2);<br><br>      Rect perceptionRect = new Rect(halfPos, new Vector2(_boids.MaxPerceptionRadius, _boids.MaxPerceptionRadius));<br>      <br>      _quadTree.QueryRange(perceptionRect, _boids.Positions, foundNeighbors);<br>      <br>      for (int j = 0; j &lt; foundNeighbors.Length; j++)<br>      {<br>          int neighborIndex = foundNeighbors[j];<br>          if (neighborIndex != i) // Avoid to add itself.<br>          {<br>              _neighborsArray[neighborIdx] = neighborIndex;<br>              neighborIdx++;<br>              _neighborsCounts[i]++;<br>          }<br>      }<br>      foundNeighbors.Dispose();<br>  }<br><br>  // The jobs will be scheduled in the next step using these arrays...<br>}</pre><p>Once the data was ready, I launched the jobs in parallel. Since each job works on its own slice of data, there’s no memory contention, so everything runs safely.</p><p>Finally, after the jobs are finished, I update each entity’s Transform.</p><p><em>Note: below is an excerpt that focuses specifically on how the alignment behavior is computed using Unity’s Job System. The code shows how the job is defined, scheduled, and how the result is retrieved. Other behaviors like cohesion, separation, attraction, and so on follow the same pattern, for the sake of clarity, only alignment is shown here.</em></p><pre>public class Flocking : MonoBehaviour<br>{<br>  private NativeArray&lt;JobHandle&gt; _boidsJobHandles;<br>  private JobHandle _alignmentJob;<br><br>  void Update()<br>  {<br>    // Ensure the previous job is completed before accessing its data again<br>    _alignmentJob.Complete();<br><br>    // Rebuild QuadTree and prepare neighbor arrays (see previous section)...<br><br>    // Start the alignment job with all required data and parameters<br>    _alignmentJob = AlignmentJob.Begin(_boids.Positions,<br>        _boids.Velocities,<br>        _neighborsArray,<br>        _neighborsCounts,<br>        _neighborsStartIndices,<br>        _boids.Alignment.Steering,<br>        _boids.Behavior.MovementAccuracy,<br>        _boids.Alignment.PerceptionRadius,<br>        _boids.Alignment.PerceptionAngle,<br>        _boids.Alignment.MinDistanceWeight,<br>        _boids.Alignment.MaxDistanceWeight,<br>        _boids.Alignment.DesiredMagnitude,<br>        _boids.Alignment.MaxSteeringForce,<br>        _boids.Alignment.ScaleForce);<br><br>  }<br><br>  void LateUpdate()<br>  {<br>    // Wait for the job to finish before applying its results<br>    // Using LateUpdate gives the job as much time as possible to execute,<br>    // since it&#39;s the last method called in the game loop<br>    _boidsJobHandles = new NativeArray&lt;JobHandle&gt;(1, Allocator.TempJob);<br>    _boidsJobHandles[0] = _alignmentJob;<br>  <br>    JobHandle boidsJobDependencies = JobHandle.CombineDependencies(_boidsJobHandles);<br><br>    // Once the jobs are done, apply results to the Transform of each boid<br>    // (not shown here for brevity)<br>  }<br>}<br><br>[BurstCompile(CompileSynchronously = true)]<br>public struct AlignmentJob : IJobParallelFor<br>{<br>  private NativeArray&lt;float2&gt; _alignmentSteering;<br><br>  [ReadOnly] private NativeArray&lt;float2&gt; _positions;<br>  [ReadOnly] private NativeArray&lt;float2&gt; _velocities;<br>  [ReadOnly] private NativeArray&lt;int&gt; _neighborsArray;<br>  [ReadOnly] private NativeArray&lt;int&gt; _neighborsCount;<br>  [ReadOnly] private NativeArray&lt;int&gt; _neighborsStartIndices;<br>  [ReadOnly] private int _movementAccuracy;<br>  [ReadOnly] private float _perceptionRadius;<br>  [ReadOnly] private float _perceptionAngle;<br>  [ReadOnly] private float _minDistanceWeight;<br>  [ReadOnly] private float _maxDistanceWeight;<br>  [ReadOnly] private float _desiredMagnitude;<br>  [ReadOnly] private float _maxSteeringForce;<br>  [ReadOnly] private float _scaleForce;<br>  <br>  public static JobHandle Begin(NativeArray&lt;float2&gt; positions, <br>    NativeArray&lt;float2&gt; velocities, <br>    NativeArray&lt;int&gt; neighborsArray,<br>    NativeArray&lt;int&gt; neighborsCount,<br>    NativeArray&lt;int&gt; neighborsStartIndices,<br>    NativeArray&lt;float2&gt; steering,<br>    int movementAccuracy,<br>    float perceptionRadius,<br>    float perceptionAngle,<br>    float minDistanceWeight,<br>    float maxDistanceWeight,<br>    float desiredMagnitude,<br>    float maxSteeringForce,<br>    float scaleForce)<br>  {<br>    var job = new AlignmentJob()<br>    {<br>      _positions = positions,<br>      _velocities = velocities,<br>      _neighborsArray = neighborsArray,<br>      _neighborsCount = neighborsCount,<br>      _neighborsStartIndices = neighborsStartIndices,<br>      _alignmentSteering = steering,<br>      _movementAccuracy = movementAccuracy,<br>      _perceptionRadius = perceptionRadius,<br>      _perceptionAngle = perceptionAngle,<br>      _minDistanceWeight = minDistanceWeight,<br>      _maxDistanceWeight = maxDistanceWeight,<br>      _desiredMagnitude = desiredMagnitude,<br>      _maxSteeringForce = maxSteeringForce,<br>      _scaleForce = scaleForce<br>    };<br><br>    return IJobParallelForExtensions.Schedule(job, positions.Length, 32);<br>  }<br><br>  public void Execute(int index)<br>  {<br>    float2 currentPos = _positions[index];<br>    float2 currentVel = _velocities[index];<br>    <br>    int count = _neighborsCount[index];<br>    int startIdx = _neighborsStartIndices[index];<br><br>    if (count &lt;= 0)<br>    {<br>      _alignmentSteering[index] = float2.zero;<br>      return;<br>    }<br><br>    bool ran = false;<br>    float2 desired = float2.zero;<br>    <br>    for (int i = 0; i &lt; count &amp;&amp; i &lt; _movementAccuracy; i++)<br>    {<br>      int neighborIndex = _neighborsArray[startIdx + i];<br><br>      float2 neighborPosition = _positions[neighborIndex];<br>      float2 distToNeighbor = currentPos - neighborPosition;<br>      <br>      float distance = math.length(distToNeighbor);<br>      if (distance &lt; _perceptionRadius)<br>      {<br>        float2 dirToNeighbor = (_positions[neighborIndex] - currentPos);<br>        dirToNeighbor = math.normalize(dirToNeighbor);<br><br>        float2 forward = math.normalize(currentVel);<br>        float dot = math.dot(forward, dirToNeighbor);<br>        float angleToNeighbor = math.acos(dot);<br>        float angleDegToNeighbor = math.degrees(angleToNeighbor);<br>        <br>        if (angleDegToNeighbor &lt; (_perceptionAngle / 2))<br>        {<br>          float weightedDistance = math.remap(0f, _perceptionRadius, _minDistanceWeight, _maxDistanceWeight, distance);<br>          <br>          desired += math.normalize(_velocities[neighborIndex]) * weightedDistance;<br>          ran = true;<br>        }<br>      }<br>    }<br><br>    if (ran)<br>    {<br>      desired = math.normalize(desired) * _desiredMagnitude;<br>      <br>      float2 steering = desired - currentVel;<br>      <br>      float steeringMagnitude = math.length(steering);<br>      if (steeringMagnitude &gt; _maxSteeringForce)<br>          steering = math.normalize(steering) * _maxSteeringForce; <br><br>      steering *= _scaleForce;<br><br>      _alignmentSteering[index] = steering;<br>    }<br>    else<br>    {<br>      _alignmentSteering[index] = float2.zero;<br>    }<br>  }<br>}</pre><p><strong>How the job is defined and scheduled<br></strong>In Unity’s Job System, defining a job means creating a struct that implements a specific interface — in this case, IJobParallelFor. This interface tells Unity that the job will be executed <strong>in parallel</strong>, once for each index in the range you provide. In our simulation, that means one execution per <em>boid</em>.</p><p>The struct AlignmentJob represents this definition. It contains all the input data (like positions, velocities, and neighbors) and one output array where each <em>boid</em>’s steering result will be stored.</p><p>To run the job, we use the Schedule() method. This not only starts the job but also allows us to specify the total number of iterations (i.e., the number of <em>boids</em>) and a batchCount.<br> The batchCount defines how many iterations each worker thread should process at a time. Smaller values can increase parallelism, while larger values reduce scheduling overhead. In practice, a value like 32 is a good balance between performance and responsiveness.</p><p>Before scheduling a new job in Update(), we call .Complete() on the previous frame’s alignment job. This ensures that the job has fully finished before we try to read from or write to any of its data (such as _alignmentSteering). Unity’s jobs run asynchronously, so accessing memory that&#39;s still in use by a running job could lead to <strong>race conditions or crashes</strong>,Complete() prevents that by blocking until the job has safely finished.</p><p>Later in the frame, we wait for the current job to complete in LateUpdate(). This is intentional: since LateUpdate() is the last step in Unity&#39;s frame loop, it gives the job <strong>as much time as possible</strong> to run in the background before we need the results.<br> This approach helps maximize parallel execution time while minimizing the risk of stalls or delays on the main thread.</p><p>Once scheduled, Unity runs the job concurrently across CPU threads, using the data we’ve passed in. The Execute() method inside the job is where the actual computation for each <em>boid</em> takes place. Although we won’t go into its internal logic here, it’s important to understand that this is the function that Unity will call repeatedly, once for each index, in parallel, to perform the alignment calculation.</p><p>This setup ensures high performance and scalability while keeping the logic thread-safe and deterministic.</p><p><strong>Job System best practices<br></strong>When working with Unity’s Job System, following a few best practices can make the difference between a simulation that just runs, and one that runs efficiently and safely.</p><ul><li><strong>Profile early and often</strong><br>Before optimizing blindly, it’s essential to measure. Use Unity’s <strong>Profiler</strong> to identify real bottlenecks in your simulation, whether they’re related to physics, rendering, or CPU-bound logic like boid behaviors.<br>The Profiler helps you see exactly where time is spent in each frame, so you can determine <strong>which parts benefit most from parallelization</strong>. Don’t assume, measure first.</li><li><strong>Avoid overkill</strong><br>While Unity’s Job System is powerful, not every task is worth offloading. Very small or infrequent computations may not benefit from parallelization, and in some cases, the setup cost (allocating data, scheduling, synchronizing) can outweigh the gains.<br>Jobs are best reserved for workloads that are repeated, data-heavy, and scale with the number of agents or elements, like our per-<em>boid</em> behavior computations.</li><li><strong>Manage memory responsibly</strong><br>NativeArray and other Native* containers provide high performance but require <strong>manual memory management</strong>.<br>Always deallocate them when you&#39;re done using them, otherwise, you&#39;ll create memory leaks that can go unnoticed during development.<br>Where possible, try to allocate once and reuse across frames, instead of reallocating every update. This reduces pressure on the garbage collector and improves frame consistency.</li></ul><h4><strong>7. Reflections and next steps</strong></h4><p>From a model born in 1986, we’ve built a modern, interactive, scalable simulation that can handle tens of thousands of <em>agents</em> with believable emergent behavior.</p><p>Thanks to a combination of:</p><ul><li>simple yet powerful rules (alignment, cohesion, separation, etc.),</li><li>spatial optimizations like <em>QuadTree</em>,</li><li>parallel computation via Unity Jobs + Burst Compiler,</li><li>and real-time interactivity (predators, explosions, attraction),</li></ul><p>we’ve created a fluid, engaging simulation that’s ready for all sorts of uses.</p><p><strong>Future ideas<br></strong>This simulation can be a launchpad for more advanced projects. Some ideas:</p><ul><li><strong>Learning-based flocking: </strong>use machine learning to evolve behaviors toward goals.</li><li><strong>Gameplay integration: </strong>use <em>boids</em> for dynamic NPCs, enemy swarms, or ambient crowd systems.</li><li><strong>Biological or generative art: </strong>simulate natural phenomena or create interactive visual experiences.</li></ul><p><strong>Source code<br></strong>Want to try it out, break it down, or just have fun scaring <em>boids</em> with a mouse click?<br>You can find the full project here:<br><a href="https://github.com/fgrenoville/2D-Flocking-Simulation">https://github.com/fgrenoville/2D-Flocking-Simulation</a></p><p><strong>Thanks for reading!</strong><br>If you enjoyed the article, consider leaving a like, a comment, or sharing it.<br>Got questions about the code, optimizations, or want to build on it? I’d love to chat!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30ef13aea78b" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/unleashing-massive-flocks-with-unity-30ef13aea78b">Unleashing Massive Flocks with Unity</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>