< Return to Engineering Blog
Engine ArchitectureNOV 17, 2026 // 6 MIN READ

UE5 Swept Melee Collision: SweepMultiByChannel C++

Architect high-performance UE5 melee hit detection in C++ using SweepMultiByChannel, inline allocators, sub-step interpolation, and Chaos BVH optimization.

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.

cpp
#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.

KEY ARCHITECTURAL TAKEAWAYS

  • 01.Sweep analytic primitives (capsules or boxes) rather than complex meshes to ensure efficient Chaos BVH broad-phase and narrow-phase traversal.
  • 02.Eliminate heap fragmentation by backing FHitResult arrays with stack-allocated inline memory (TInlineAllocator<16>).
  • 03.Sub-step high-speed rotational arcs using FQuat::Slerp to eliminate frame-rate-dependent tunneling during frame spikes.
  • 04.Set combatant hurtboxes to ECR_Overlap and physical walls to ECR_Block so the sweep slices through all targets while stopping on hard geometry.
  • 05.Maintain a frame-indexed TSet<TWeakObjectPtr<AActor>> across the attack notify duration to prevent multi-frame phantom double hits.

FREQUENTLY ASKED QUESTIONS

Why does SweepMultiByChannel stop collecting hits after the first blocking hit?

By design in Unreal Engine's collision architecture, Multi traces are constructed to gather all overlapping hits along the ray or sweep until a blocking hit is reached. Once a blocking hit occurs, the sweep is physically obstructed, terminating the query at that distance. To allow a weapon to slice through multiple enemies simultaneously, all character combat hitboxes must respond to the melee Trace Channel with Overlap (ECR_Overlap), reserving Block (ECR_Block) strictly for static environment geometry or parry barriers.

Why is passing FQuat faster than FRotator to sweep functions?

Under the hood, Chaos physics represents 3D orientations natively as unit quaternions (FQuat) to avoid gimbal lock and streamline matrix rotations. When you pass an FRotator to World collision query functions, the engine converts that rotator into an FQuat internally before executing BVH intersection tests. Supplying an FQuat directly removes redundant Euler-to-Quaternion trigonometric calculations.

How does TInlineAllocator<16> optimize high-frequency melee traces?

Standard TArray allocations request dynamic heap memory when constructed without pre-sizing, which triggers CPU cache misses and heap fragmentation when executed repeatedly inside a weapon's tick loop. TArray<FHitResult, TInlineAllocator<16>> reserves memory for 16 FHitResult structs directly on the thread stack. Unless an attack hits more than 16 individual targets in a single sub-step, zero dynamic memory allocations occur.

When should you switch from synchronous sweeps to asynchronous scene queries?

Synchronous sweeps (SweepMultiByChannel) execute immediately on the game thread, which is required for tight melee combat where immediate gameplay feedback (hit-stop, blood decals, sound triggers) must sync to the exact animation tick. Asynchronous queries (AsyncSweepByChannel) should only be used for non-immediate combat checks—such as AI peripheral vision, broad sensory sweeps, or large-scale ambient trajectory simulations where a 1-to-2 frame result latency is acceptable.

// CONNECTED_ENGINEERING_DOSSIERS

All Articles >