Dibya Sarothi
Dibya Sarothi
Software ArchitectureAugust 2026•6 min read

Engineering Deterministic Hierarchical State Machines for 2D Combat Loops

Managing input buffering, physics ticks, and zero-allocation combat states in Unity C#.

Author: Dibya Sarothi • Systems & Software Engineer
Abstract

“Action games live or die by the responsiveness of their combat loops. This technical paper documents the architectural patterns developed during the creation of Ashenfall, demonstrating how Hierarchical Finite State Machines (HFSM) and non-allocating 2D physics casts eliminate frame drops and input latency.”

The Trap of Giant Switch Statements in Game Loops

Beginner game architectures often attempt to manage player and boss logic using monolithic switch-case statements or boolean flags inside 'Update()'. As attack phases, parry frames, coyote time, and hit-stop are introduced, state explosion occurs, resulting in untestable code and erratic bugs.

By decomposing characters into discrete, hierarchical state objects, each state encapsulates its own entry, physics tick, animation trigger, and exit transitions.

Zero-Allocation Physics Casts

In high-speed combat with dozens of slashes and projectiles, standard Unity queries like 'Physics2D.OverlapCircleAll' allocate temporary array buffers on the managed C# heap on every single frame. This triggers frequent Garbage Collector (GC) collections, resulting in micro-stutters that ruin the player's timing.

By employing pre-allocated array buffers with 'Physics2D.OverlapBoxNonAlloc', combat queries execute with exactly zero heap allocation, maintaining smooth 60+ FPS performance even on low-end hardware.

Key Engineering Conclusions
  • Hierarchical state machines isolate complex combat logic into testable, modular components.
  • Zero-allocation memory discipline in real-time loops is critical for eliminating frame-time spikes.
  • Kinematic input integration with input buffering provides tactile, fair gameplay feel.
Cited References & Standards
  • [1] Nystrom, R. (2014). Game Programming Patterns: State.
  • [2] Unity Technologies (2025). Universal Render Pipeline & Memory Profiling Guidelines.