Engineering Core Gameplay in Fighting Games: Input, Hit Detection, and Combos
This article explores the engineering implementation of core mechanics in fighting game development. It provides a comprehensive guide covering scope definition, system architecture separation, input buffering, finite state machines, collision boxes, frame data, combo cancel systems, energy management, AI difficulty scaling, and round management. Additionally, it offers practical workflows for AI-assisted prototyping and highlights common development pitfalls to avoid.
1. Requirements Definition and Scope
Fighting games feature high operational density and tightly coupled rules. During the prototyping phase, failing to define scope first often leads to significant effort spent on character animations and visual effects without forming a complete, playable loop. A verifiable minimum viable product (MVP) usually includes the following:
- Two playable characters, each with a similar set of basic actions;
- A single stage (e.g., a nighttime rooftop or an indoor arena) to control the complexity of art and collision boundaries;
- Two modes: single-player versus CPU and local two-player;
- Three difficulty levels: Simple, Standard, and Hard;
- A best-of-three round system;
- Core mechanics including blocking, throws, jumping, dashing, air hitstun, and combo cancels;
- Directional combo special moves, full-meter super moves, and close-up camera triggers for super moves;
- Pause and match result settlement interfaces.
Once the scope is determined, every feature must answer two questions: Does it affect the core game feel? Can it be independently verified without modifying other modules? If the answer to either is unclear, it should be postponed to the next version.
2. System Architecture: Separating Input, Logic, and Presentation
Fighting games are extremely sensitive to timing. It is recommended to split the system into three layers:
- Input Layer: Collects device signals and converts them into a unified “key frame” record;
- Logic Layer: Advances the battle state at a fixed time step, handling movement, hit detection, damage, and state transitions;
- Presentation Layer: Plays animations, sound effects, visual effects, and camera movements. It only reads the state from the logic layer and does not modify battle data in reverse.
The advantage of this division is that the logic layer can run independently of the visuals. During testing, you can input a recorded sequence of key presses to directly verify the results without manual frame-by-frame observation.
2.1 Fixed Time Step
Battle logic should update at a fixed frequency, typically set to 60 frames per second. If the system relies directly on actual elapsed time, device performance fluctuations will cause the same input to produce different results, and combo hit detection windows will drift. A fixed time step combined with an accumulator approach solves this problem:
FIXED_DT = 1 / 60accumulator = 0.0def update(frame_time):global accumulatoraccumulator += frame_timewhile accumulator >= FIXED_DT:simulate_one_frame() # Advance battle logic by one frameaccumulator -= FIXED_DT
Pause, slow motion, and super move close-ups can all be achieved by adjusting the update frequency or pausing the logic layer, without modifying the battle rules themselves.
3. Input Handling: Directional Command Buffering
When a player inputs a sequence like “down, down-forward, forward + attack” on a keyboard or gamepad, the three directional inputs cannot perfectly occur on the same frame. Therefore, the system needs to save the input history of the last few frames and check if the sequence appeared in order within a time window. This is input buffering.
The window length is usually 10 to 15 frames. If the window is too short, commands will be difficult to trigger; if too long, the system may misinterpret the player’s normal movement as a command.
BUFFER_WINDOW = 12 # Unit: framesdef match_motion(history, sequence, window=BUFFER_WINDOW):"""Match directional sequence in order within the recent window frames"""recent = history[-window:]idx = 0for frame in recent:if frame.direction == sequence[idx]:idx += 1if idx == len(sequence):return Truereturn FalseQUARTER_CIRCLE_FORWARD = ["down", "down_forward", "forward"]
Note the following during implementation:
- Directions need standardization; “forward” and “backward” must be converted based on the character’s facing direction;
- Continuous frames holding the same direction should be merged, otherwise sequence matching will cause misjudgments;
- After a special move command is consumed, the history should be cleared to prevent the same input from triggering two actions.
4. Battle State Machine
Every action of a character should belong to a clear state, such as idle, crouch, walk, jump, block, attack, hitstun, airborne, or knockdown. Using a state machine clearly constrains which actions can occur in which states, preventing logical contradictions like “blocking while being hit”.
TRANSITIONS = {"idle": ["walk", "crouch", "jump", "block", "attack", "dash", "throw"],"attack": ["idle"], # Returns to idle after action ends"hitstun": ["idle", "airborne"],"airborne": ["knockdown", "idle"],"knockdown": ["idle"],}def change_state(char, new_state):if new_state not in TRANSITIONS.get(char.state, []):return False # Rejects invalid transitions and logschar.state = new_statechar.state_frame = 0return True
The value of a state machine is that it makes issues traceable. When a hit result is unexpected, you only need to check the character’s state and transition record at that frame to determine whether the error is in the input layer, hit detection layer, or state layer.
5. Hit Detection System: Collision Boxes and Frame Data
Attacks in fighting games are typically described by three types of rectangular areas:
- Hurtbox: The area of the character’s body that can be hit, usually always active;
- Hitbox: The effective damage area during an attack, only active during active frames;
- Pushbox: Determines the horizontal distance when two characters are close, preventing overlap.
Every attack also needs to define frame data. Common terms include:
- Startup: The number of frames from input to the first appearance of the hitbox;
- Active: The number of frames the hitbox exists and can connect;
- Recovery: The number of frames the character cannot act after the attack ends;
- Hitstun/Blockstun: The forced freeze frames for both parties after a hit or block.
class Attack:def __init__(self, damage, startup, active, recovery,hitstun, blockstun, hitbox):self.damage = damageself.startup = startupself.active = activeself.recovery = recoveryself.hitstun = hitstunself.blockstun = blockstunself.hitbox = hitbox # Rectangle: x, y, w, h, relative to character originself.total = startup + active + recoverydef is_hitbox_live(self, frame):return self.startup <= frame < self.startup + self.active
Frame data design requires basic balance: longer startup frames make an attack easier to punish; longer recovery frames increase the cost. These values should be placed in configuration files for easy adjustment, not hardcoded.
5.1 Simultaneous Hit Handling
Two characters’ hitboxes may overlap with the opponent’s hurtbox on the same frame. Rules must be agreed upon in advance, for example:
- If both hit each other on the same frame, both take damage and enter hitstun (a trade);
- If one attack hits during the opponent’s startup frames, it is judged as a “counter hit”, granting additional hitstun;
- Hits against a blocking state are processed according to block rules and cannot be directly counted as a successful hit.
Once the rules are set, they should be written as test cases and rerun every time the hit detection code is modified.
6. Combos and Cancel Mechanics
Combos are the primary form of expression in fighting games. Implementing combos typically requires three elements:
- Hit Confirmation: After an attack hits, the system records that “this attack has made contact”, allowing subsequent actions to chain;
- Cancel Window: During the recovery frames of an attack, there is a period where transitioning to other actions is allowed, known as the cancel window;
- Damage Scaling: In the same combo, the damage of subsequent attacks decreases progressively to prevent a single combo from dealing excessive damage.
def can_cancel(attack, state_frame, hit_confirmed):if not hit_confirmed:return False# Only allow cancel during the first half of recovery to prevent infinite comboscancel_start = attack.startup + attack.activecancel_end = cancel_start + attack.recovery // 2return cancel_start <= state_frame < cancel_enddef scaled_damage(base, combo_hits):scale = max(0.4, 1.0 - 0.1 * (combo_hits - 1)) # Minimum retains 40% damagereturn int(base * scale)
The specific values for damage scaling are design parameters and should be adjusted based on playtesting. During prototyping, you can fix a conservative set of values first, and then observe through replay whether the combo length is reasonable.
7. Energy System and Super Moves
The energy meter usually fills when attacks hit, when taking damage, or when blocking. Once full, the player can execute a super move. The energy growth rules need separate design:
- Energy gained from hitting should be lower than energy gained from being hit, otherwise rushdown characters will become unbalanced;
- Energy gained from blocking should be minimal to prevent players from turtling to build meter;
- The energy cap is fixed, and excess is not accumulated.
When a super move is triggered, a brief close-up camera and time stop usually occur. In implementation, you can pause the logic layer for a few frames upon trigger while switching the camera and playing visual effects. Input buffering during this time must be preserved to prevent the player’s inputs from being dropped.
8. AI Opponent and Three Difficulty Levels
Single-player opponents need to adjust their reaction capabilities based on difficulty, rather than simply increasing damage. The three difficulty levels can be distinguished by the following parameters:
| Parameter | Simple | Standard | Hard |
|---|---|---|---|
| Reaction Delay (frames) | Longer | Medium | Shorter |
| Decision Interval (frames) | Longer | Medium | Shorter |
| Block Success Rate | Lower | Medium | Higher |
| Combo Complexity | Basic combos only | Includes cancels | Includes cancels and super moves |
| Throw Frequency | Rare | Moderate | Frequent |
During implementation, the AI should not directly read the opponent’s full internal state. It should make decisions using the same information sources as the player, such as currently visible state, distance, and recent actions. This prevents unfair situations where “the AI knows the player’s next move” and makes testing closer to real matches.
Decision-making can usually be divided into several layers: whether to approach, whether to block, whether to attack, and which action to choose. Each layer should have a certain degree of randomness, but the random seed should be fixable to facilitate reproducing issues.
9. Local Multiplayer and Round System
Local two-player versus requires maintaining separate input mappings for both players. The two sets of keys should not share the same key bindings, otherwise key conflicts are likely when operating on the same keyboard. When controllers are connected, they should be bound to players by device ID, not by connection order.
The round system can adopt a best-of-three format, with the following flow:
- Before the round starts, both parties’ positions and states are reset, and energy meters are cleared or retained according to rules;
- During the round, if either party’s HP reaches zero, the round ends;
- If both reach zero simultaneously, it can be judged as a Double KO, and an extra round is added or a draw is declared according to rules;
- After one party wins two rounds, the match settlement begins.
The round timer also needs to be managed uniformly in the logic layer. When time runs out, the party with more remaining HP wins; if HP is equal, it is a draw.
10. Pause and Settlement
The key to the pause function is freezing the logic layer, not the rendering. When paused, advancing battle frames should stop, but UI responsiveness should remain. When resumed, the battle state should be exactly the same as before the pause, otherwise issues like broken combos or dropped inputs will occur.
The settlement interface usually displays the match result, number of rounds, highest combo count, total damage dealt, and super move usage count. This data should be tracked in the logic layer and read by the presentation layer, avoiding duplicate calculations in the UI code.
11. AI-Assisted Development Workflow
AI-assisted development can significantly speed up prototyping, but the generated code requires strict validation, especially parts related to hit detection and timing. The following workflow is recommended:
- Write a requirements list first, clarifying characters, modes, rules, and value ranges, then let the AI generate code module by module, handling only one module at a time;
- Write unit tests for each module, such as input buffer match results, frame data boundary values, and damage scaling limits;
- Use recorded inputs for regression testing; the same input sequence should produce the same results after modifications;
- Manually check the positions and sizes of collision boxes, because the coordinates generated by models often do not match the visual proportions of the characters;
- Centralize all numerical parameters in configuration files, do not scatter them throughout the code;
- Commit a version record every time a module is completed for easy rollback.
AI-generated content cannot replace an understanding of the rules. Developers need to be clear about the assumptions behind every piece of code, otherwise it will be difficult to locate problems when they arise.
12. Common Issues and Mitigation Methods
- Unstable game feel: Usually comes from frame-rate dependent movement calculations or inconsistent input buffer lengths; you should switch to a fixed time step;
- Combos cannot connect: mostly…
