Building a Complete Combat System in a General-Purpose Game Engine

    A maintainable combat system requires more than a collection of skills. This article outlines a layered, data-driven architecture covering attributes, state machines, skill execution, hit detection, damage resolution, presentation, and network synchronization. It also explains performance practices, debugging tools, cloud infrastructure support, and a phased implementation roadmap for scaling combat content without repeated architectural rewrites.

    1. Combat Is a Collection of Subsystems

    Many teams treat combat development as “implementing a few skills,” only to rewrite the system when character counts, skill counts, or multiplayer requirements grow. A combat system is actually a collection of interconnected subsystems: attributes and numerical rules, states and behaviors, skills and effects, hit detection and resolution, presentation feedback, network consistency, configuration, and tooling.

    Its complexity comes less from individual algorithms than from combinatorial growth and timing dependencies. The same skill must behave correctly across different character states, target counts, and network latency conditions.

    The first principle is therefore not “implement quickly,” but “define clear boundaries.” With well-defined layers and responsibilities, adding characters, states, or multiplayer support becomes a localized extension rather than a system-wide rewrite.

    2. A Layered Architecture

    Organize the system into four layers, keeping dependencies unidirectional:

    1. Data layer: Attribute definitions, skill configurations, effect configurations, loot tables, and progression curves. Keep numerical values in data rather than hardcoding them in logic.
    2. Logic layer: Attribute calculations, state machines, skill execution, hit detection, and resolution. This layer contains gameplay logic and holds no references to rendering objects.
    3. Presentation layer: Animation, visual effects, audio, camera shake, and floating combat text. It subscribes to logic events without modifying gameplay results.
    4. Synchronization layer: Network serialization, authoritative decisions, client prediction, and rollback.

    The essential constraint is that the logic layer must not directly call presentation interfaces. Instead, it emits semantic events such as “hit confirmed” or “entered hit stun.” The presentation layer decides how to display them.

    This separation is the foundation of long-term maintainability.

    3. Attributes and the Calculation Pipeline

    An attribute system must handle three concerns: base values, temporary modifiers, and calculation order.

    A practical model is base value + modifier list + ordered aggregation. Each modifier carries a source identifier and priority, with support for stacking, replacement, mutual exclusion, and expiration:

    1. FinalValue = Base × (1 + ΣPercentAdd) × Π(1 + PercentMul)
    2. + ΣFlatAdd

    Key implementation practices include:

    • Traceable sources: Record the applying entity, skill instance, and remaining duration for each modifier. This supports debugging and rollback after errors.
    • Dirty-flag caching: Mark attributes as dirty when they change, then recalculate lazily when read. Avoid traversing every modifier every frame.
    • Change events: Publish attribute-change events for health bars, AI decisions, and achievement tracking instead of having each consumer poll independently.

    4. Hierarchical State Machines and Behavior

    Represent character behavior with a hierarchical state machine, with locomotion at the upper level and combat actions beneath it. This scales more cleanly than a single large switch statement.

    • Each state explicitly defines its entry conditions, update logic, exit conditions, and allowed interruptions.
    • Introduce interruption priorities, such as hit stun > dodge > basic attack > movement. Lower-priority states cannot interrupt higher-priority states.
    • Route every transition through a single entry point that coordinates animation montages, hit-detection window changes, and event publication. Centralized transition handling prevents incomplete cleanup from leaving characters stuck in a state.
    1. tryTransition(nextState):
    2. if nextState.priority < current.priorityLocked: return false
    3. current.onExit()
    4. current = nextState
    5. current.onEnter()
    6. broadcast(StateChanged(current))

    Animation coordination should still respect the layer boundary: gameplay transitions emit events, while presentation handles the corresponding animation.

    5. Configuration-Driven Skills and Effects

    Skills should use configuration plus a generic executor, rather than a separate hardcoded class for every skill. A skill consists of timeline segments containing markers for effects, hit detection, movement, audio, and other actions.

    Effects should be atomic. Damage, healing, modifier application, displacement, summoning, and resource consumption are independent effect types that can be combined through configuration.

    A tag system, using tags such as Damage.Physical, Target.Enemy, and Uninterruptible, supports queries and filtering. Requirements such as “immune to crowd control” or “affects flying units only” can then be expressed as data.

    1. Skill {
    2. id, cost, cooldown, tags
    3. timeline: [
    4. { t=0.00, event=PlayAnim, param=attack_01 },
    5. { t=0.20, event=SpawnHitbox, param={shape=arc, range=2.5, arc=120} },
    6. { t=0.35, event=ApplyEffect, param={type=Damage, value=atk*1.2} },
    7. { t=0.60, event=Consume, param={resource=stamina, value=15} }
    8. ]
    9. }

    Skill instances manage cooldowns and resource consumption, including multiple charges, shared cooldown groups, and rollback when resource consumption fails.

    6. Hit Detection and Damage Resolution

    Hit detection and resolution must remain separate. Detection answers “Who was hit, and on which frame?” Resolution answers “How much damage was dealt?”

    • Detection shapes: Support spheres, boxes, sectors, and capsule sweeps. Multi-hit skills use active windows spanning consecutive frames and maintain an already-hit set to prevent unintended duplicate resolution against the same target.
    • Frame-rate independence: Express detection windows in normalized time so differences in frame rate do not alter the number of hit stages.
    • Resolution pipeline: Use a fixed sequence: base value → additive bonuses → multiplicative bonuses → resistance/damage reduction → critical hits and variance → rounding and minimum limits. Document this order to prevent recurring disagreements between designers and programmers.
    • Immutable snapshots: Snapshot target attributes at resolution time so multiple effects within the same frame do not interfere with one another’s calculations.

    7. Event-Driven Presentation

    The logic layer publishes semantic events, and the presentation layer consumes them through an event bus.

    This allows new impact effects, camera shake, and audio layers to be added without changing combat logic. Gameplay also continues to function when presentation is disabled, whether for a low-spec mode or a server without rendering.

    That independence is a requirement for a headless authoritative server, not merely an architectural preference.

    8. Network Synchronization and Consistency

    For multiplayer combat, use a server-authoritative model. Clients predict input responses and presentation, while the server performs hit detection and resolution. Results return as state snapshots or events.

    Important considerations include:

    • Critical combat values are calculated only by the authoritative side. Client prediction improves responsiveness but must support rollback.
    • Sequence numbers and acknowledgments help reconcile predicted and authoritative results. When discrepancies exceed a threshold, apply smooth correction rather than an abrupt snap.
    • Random outcomes, including critical hits and damage variance, use seeds controlled by the authoritative side to prevent client and server results from diverging.

    Even a single-player project benefits from retaining this abstraction, keeping future multiplayer changes manageable.

    9. Performance and Engineering Practices

    • Data-oriented layout: Store frequently accessed attributes and states in compact arrays to reduce random memory access and allocation.
    • Avoid hot-path allocations: Reuse pooled objects and temporary containers during hit detection and effect execution.
    • Observability: Build combat debugging views for hit shapes, state stacks, attribute aggregation details, and event timelines. These are more effective than guessing at problems after they occur.
    • Configuration and tooling: Keep skill configuration tables under version control. Use continuous integration to validate reference integrity, numerical ranges, and valid tags.
    • Automated verification: Write unit tests for critical formulas and state transitions. Use recorded gameplay replays for regression testing to check that changes preserve established combat behavior and feel.

    10. Data and Server Infrastructure

    When combat data must be shared across clients and servers, configuration versions rolled out gradually, or behavior analyzed, general-purpose cloud services can provide supporting infrastructure:

    • Object storage distributes configuration bundles and replay files.
    • Message queues absorb bursts of combat-log submissions.
    • Container platforms deploy headless authoritative combat services with elastic scaling.
    • Logging, monitoring, and alerting services track error rates and latency.

    Baidu AI Cloud provides services in these general categories and can be considered during infrastructure evaluation. Consult the official documentation for specifications, pricing, and regional availability; this article assumes no particular service parameters.

    11. Common Pitfalls

    1. Logic and presentation call into each other, preventing a headless server build.
    2. Numerical formulas are scattered across the codebase, making resolution results difficult to reproduce.
    3. State cleanup is incomplete, causing permanent hit stun or skills stuck on cooldown.
    4. Hit detection depends on frame rate, producing inconsistent behavior across devices.
    5. Skills are hardcoded, so implementation costs grow with each new character.
    6. Debugging visualizations are missing, leaving developers to infer problems from logs.

    12. A Phased Implementation Roadmap

    • Phase 1: Build the attribute pipeline, state-machine skeleton, and one melee skill. Complete the loop from input to detection, resolution, and presentation.
    • Phase 2: Introduce configurable skills and effects, then extend them to ranged, area-of-effect, and crowd-control skills.
    • Phase 3: Add target selection, AI interfaces, and team and faction relationships.
    • Phase 4: Implement multiplayer authority, prediction, and rollback.
    • Phase 5: Develop tooling, automated tests, performance profiling, and workflows for scaling content production.

    Ultimately, combat-system quality is reflected in the cost of making changes. With a sound architecture, implementing the hundredth skill should cost roughly as much as implementing the first.

    Clear layering, data-driven design, and observability provide the foundation for a combat framework that supports rapid content iteration while remaining maintainable over time.