The Breakdown of Naive Traces in Action Combat
In fast-paced melee combat like Project Ronin, standard hit-detection implementations collapse under high angular velocities. Naive approaches typically rely on two flawed patterns: attaching a dynamic trigger volume to the weapon mesh or firing a single-frame line trace between two weapon sockets during an animation notify. Both produce severe gameplay artifacts. Trigger volumes lag behind the skeletal mesh by a frame depending on tick group execution order, causing phantom hits or registration latency. Socket line traces, on the other hand, possess zero volume, meaning a blade can slice directly through an enemy's limb between ticks—a phenomenon known as frame tunneling. Read technical details on outlore game studio project ronin.
At Outlore, we treat melee hit registration as a continuous swept-volume protocol. Instead of querying zero-dimensional points, we extrude an oriented analytic primitive (such as an oriented capsule or box) along the motion vector traced between the weapon's previous and current bone transforms. By pairing Unreal Engine 5's SweepMultiByChannel API with rigorous transform sub-stepping and stack-allocated hit buffers, we achieve deterministic, high-speed hit detection that never tunnels, respects physical geometry, and maintains zero per-tick dynamic memory allocations. Read technical details on unity c++ engine garbage collection custom engine.
Chaos Scene Query Architecture and Swept Primitives
Unreal Engine 5 executes physics queries via the Chaos physics engine. When an actor queries the scene using SweepMultiByChannel, Chaos traverses its Bounding Volume Hierarchy (BVH) to locate potential collision pairs before running narrow-phase geometric intersection tests. The computational complexity of this narrow-phase check depends heavily on the collision shape chosen. Read technical details on unreal vs unity engine comparison game engine.
Sweeping complex polygonal meshes (bTraceComplex = true) requires Chaos to perform triangle-level intersection tests against the swept sweep hull. For an active melee sweep spanning multiple frames across dozens of characters, this spikes the scene query tick exponentially. Instead, production melee systems should sweep analytic primitives: FCollisionShape::MakeCapsule or FCollisionShape::MakeBox. Capsules are mathematically optimal because intersection tests between a swept sphere-capped cylinder and the scene's bounding volumes reduce to simple distance calculations between line segments. By keeping the shape extents tightly fitted to the blade's active edge, the BVH broad-phase can reject non-overlapping geometry rapidly, yielding sub-millisecond query durations. Read technical details on Structuring Character State Machines in C++ for Action Combat.
Transform Interpolation and Anti-Tunneling Math
When frame times fluctuate—such as when a player's machine drops from 120 FPS to 45 FPS during heavy particle loads—the distance traveled by a weapon's tip during a single animation frame can exceed several meters. Sweeping a single shape from the previous frame's transform to the current transform creates a linear extrusion that completely misses the circular arc of a sword swing, resulting in clipping and missed collisions.
To solve this, we compute an adaptive sub-step count based on angular and translational displacement. Between the previous weapon transform and the target weapon transform, we interpolate positions using linear interpolation (FMath::Lerp) and rotations using spherical linear interpolation (FQuat::Slerp). The sweep is executed in discrete segments across these intermediate matrices, guaranteeing that the extruded volume mirrors the circular trajectory of the blade arc.
Memory-Conscious C++ Sweep Implementation
Executing multiple sweeps per tick per active combatant can introduce performance problems through heap fragmentation if default TArray structures are used. By default, TArray allocates memory on the heap whenever hits exceed its initial capacity. To prevent per-tick dynamic allocations in high-frequency melee passes, we back our hit results with an inline scrap allocator: TArray<FHitResult, TInlineAllocator<16>>. This guarantees that up to 16 simultaneous hit results remain directly on the CPU stack, preserving cache locality and eliminating dynamic malloc/free overhead.
Furthermore, trace channel configurations must be handled precisely. A critical behavioral nuance of UE5's SweepMultiByChannel is that the query records every overlap along its path but terminates immediately upon encountering the first Blocking hit. In combat setups, damageable combatant collision hulls must be configured to return ECollisionResponse::ECR_Overlap to the melee trace channel, while static environment structures (walls, floors, shields) return ECollisionResponse::ECR_Block. This ensures the blade passes through all targets in its arc while cleanly deflecting off solid environment geometry.
#include "CoreMinimal.h"
#include "Engine/World.h"
#include "CollisionQueryParams.h"
#include "Engine/EngineTypes.h"
// Frame-safe, stack-allocated melee sweep with transform sub-stepping
void ExecuteMeleeSweep(
UWorld* World,
AActor* WeaponOwner,
const FTransform& PrevTransform,
const FTransform& CurrentTransform,
float BladeRadius,
float BladeHalfHeight,
ECollisionChannel MeleeChannel,
TSet<TWeakObjectPtr<AActor>>& InOutHitVictims)
{
if (!World || !WeaponOwner)
{
return;
}
// 1. Setup collision query parameters with profiling stat identifier
FCollisionQueryParams QueryParams(SCENE_QUERY_STAT(MeleeWeaponSweep), false, WeaponOwner);
QueryParams.bReturnPhysicalMaterial = true;
QueryParams.bTraceComplex = false;
QueryParams.AddIgnoredActor(WeaponOwner);
// 2. Define the analytic swept primitive (Capsule aligned with blade axis)
const FCollisionShape SweepShape = FCollisionShape::MakeCapsule(BladeRadius, BladeHalfHeight);
// 3. Calculate sub-stepping based on rotational arc magnitude
const FQuat StartQuat = PrevTransform.GetRotation();
const FQuat EndQuat = CurrentTransform.GetRotation();
const float AngularDisplacement = StartQuat.AngularDistance(EndQuat);
// Allocate at least 1 step; add sub-steps for extreme rotational sweeps
const int32 NumSteps = FMath::Clamp(FMath::CeilToInt(AngularDisplacement / FMath::DegreesToRadians(30.0f)), 1, 4);
FTransform StepStart = PrevTransform;
for (int32 StepIdx = 1; StepIdx <= NumSteps; ++StepIdx)
{
const float Alpha = static_cast<float>(StepIdx) / static_cast<float>(NumSteps);
// Spherical interpolation for orientation; linear interpolation for translation
const FVector InterpolatedPos = FMath::Lerp(PrevTransform.GetLocation(), CurrentTransform.GetLocation(), Alpha);
const FQuat InterpolatedQuat = FQuat::Slerp(StartQuat, EndQuat, Alpha);
const FTransform StepEnd(InterpolatedQuat, InterpolatedPos);
// 4. Stack-allocated hit result buffer (zero dynamic heap allocation up to 16 hits)
TArray<FHitResult, TInlineAllocator<16>> HitBuffer;
// Note: Passing FQuat directly avoids internal FRotator-to-FQuat conversion penalties
const bool bHit = World->SweepMultiByChannel(
HitBuffer,
StepStart.GetLocation(),
StepEnd.GetLocation(),
StepEnd.GetRotation(),
MeleeChannel,
SweepShape,
QueryParams
);
if (bHit || HitBuffer.Num() > 0)
{
for (const FHitResult& Hit : HitBuffer)
{
AActor* HitActor = Hit.GetActor();
if (!HitActor || InOutHitVictims.Contains(HitActor))
{
continue; // Deduplicate: already struck in this swing sequence
}
// Process damage or impact
InOutHitVictims.Add(HitActor);
// If sweep intersected blocking geometry (e.g. concrete wall, parry shield), break sub-steps
if (Hit.bBlockingHit)
{
// Trigger weapon deflection/recoil protocol here
return;
}
}
}
StepStart = StepEnd;
}
}Hit De-Duplication and Collision Matrix Protocol
A standard swing animation typically lasts between 200 and 400 milliseconds. Over this window, the collision sweep function will fire 12 to 24 times at 60 FPS. Without frame-indexed de-duplication, an enemy resting within the sword's swing volume would take damage on every single tick, resulting in instant death from a single swing.
We resolve this by maintaining an active attack sequence lifetime tracking buffer. When an attack animation begins, a designated TSet<TWeakObjectPtr<AActor>> is instantiated. On every tick of the sweep window, each struck actor is validated against this set. If present, the hit is discarded. If absent, the victim is registered, hit-stop time dilation is applied, and damage calculations are dispatched. Once the attack trail notify ends or the state machine transitions out of the attack state, the set is cleared, resetting the weapon's state for the next combo chain.