Continuous Collision Detection

Continuous collision detection (CCD) checks a body's path through a fixed step to catch contacts that discrete collision can miss between poses. Enable it on a fast body with ContinuousCollisionMode.Continuous.

Quick Read

A sphere of radius 0.5 starts at x = -2 and would move to x = +2 in one step. A stationary wall 0.1 units thick is centered at x = 0. At either end of the step, the sphere is clear of the wall. With discrete collision, it passes through.

With CCD, Gravitas sweeps the sphere along the intended path. The first contact occurs when the sphere's leading edge reaches the wall's near face, at a center position of about x = -0.55. The time of impact (TOI) is when that contact happens within the step. In this example, the collision stops the sphere's motion along X.

flowchart TB
    accTitle: One step with a fast sphere and a thin wall
    accDescr: Both modes start at x equals minus 2. Discrete reaches x equals plus 2 past the wall. Continuous sweeps the path and stops at contact near x equals minus 0.55.
    Start["Sphere starts at x = -2"]
    Start -->|"Discrete"| End["Ends at x = +2<br/>Past the wall"]
    Start -->|"Continuous"| Contact["Stops near x = -0.55<br/>At the wall"]

To enable this behavior for an existing 3D body, set its mode before stepping the world. The 2D body exposes the same property.

body.ContinuousCollisionMode =
    ContinuousCollisionMode.Continuous;

See how mode inheritance works, which path handles each target, and which counters to inspect. The source map links to the sphere-and-wall regression tests.

Public Control Surface

Set ContinuousCollisionMode on a SolidBody or SolidBody2D to choose the mode for that body. Set PhysicsSettings.DefaultContinuousCollisionMode to choose the fallback for a context.

Mode Behavior
Discrete Advances using discrete collision without a CCD sweep.
Continuous Enables CCD for eligible motion.
Auto Applies a motion threshold. For translation, the intended displacement must exceed the body's proxy radius, measured from the pivot to enclose the collider.
Inherit Uses the top parent body's explicit mode if present, then the context default. A context default of Inherit resolves to Discrete.

Body and settings assignments and settings or replay population reject undefined enum values with ArgumentOutOfRangeException before publishing them.

CCD Paths

The sphere in the example takes the stationary 3D path. For a moving target, Gravitas uses the prepared motion of both bodies to find when they meet. The tables show how the target's mobility and dimension select the sweep. A reducer is the geometry routine that tests a sweep for a hit.

SolidBody

Path Target set Reducer policy
Stationary 3D bodyless, static-role, and stationary kinematic 3D colliders Source collider proxy sphere, then shape-exact validation where supported.
Moving 3D dynamic and moving kinematic 3D bodies Prepared pair trajectories, exact validation for supported source families, conservative proxy behavior where no exact source reducer exists.
Mixed stationary 2D bodyless, static-role, and stationary kinematic 2D slabs Same reducer policy as public QueryMixed.SweepSphereAgainst2D.
Mixed moving 2D dynamic and moving kinematic 2D bodies Prepared pair trajectories, conservative mixed proxy candidate, then bounded handoff.
Kinematic active source static-style blockers and dynamic 3D/2D targets before first blocker Frame-start pose to host target pose, using the underlying dimension-local or mixed reducer.

SolidBody2D

Path Target set Reducer policy
Stationary 2D bodyless, static-role, and stationary kinematic 2D colliders Source circle sweep, refined by mover shape where needed.
Moving 2D dynamic and moving kinematic 2D bodies Prepared pair trajectories, then exact mover-shape validation for circle, capsule, AABB, convex polygon, and compound families.
Mixed stationary 3D bodyless, static-role, and stationary kinematic 3D colliders Same reducer policy as public QueryMixed.SweepCircleAgainst3D.
Mixed moving 3D dynamic and moving kinematic 3D bodies Prepared pair trajectories, conservative mixed proxy candidate, then bounded handoff.
Kinematic active source static-style blockers and dynamic 2D/3D targets before first blocker Frame-start pose to host target pose, using the underlying dimension-local or mixed reducer.

Stationary And Kinematic Targets

Which Targets Can Block a Sweep?

Static-style CCD targets include bodyless colliders, explicit static bodies, and stationary kinematic bodies. Freeze axes do not change a body's CCD role. Translational source admission follows CanTranslate; rotational source and target admission follows independent CanRotate, so a position-frozen dynamic body can still sweep changing rotational bounds. Fully locked dynamic bodies remain indexed for deterministic counterpart access but do not start CCD work.

Moving kinematic targets are captured in the same frame-prepared candidate index and piecewise trajectory model as moving dynamic targets, so their sampled pose does not depend on body registration or service order. Public sweep queries can report dynamic, kinematic, static, and bodyless targets according to normal query filters. Final CCD target admission uses the owning collision service's physical-pair gate, including collider lifecycle, authored filters, hierarchy rules, and linked-joint collision suppression.

Starting Inside a Solid

3D sphere sweeps against solid cylinders and cones retain the target's outward surface normal even when the source center is contained. Starting overlaps have zero sweep distance, and the selected surface anchor is retained independently of world-point representability. Direct primitives and compound parts follow the same rule. Queries report the geometric hit for either travel direction; CCD uses its normal to permit escape and block motion deeper into the solid.

When the Host Moves a Kinematic Body

For kinematic active-source CCD, hosts write deterministic target transforms before context.LateSimulate(). Gravitas captures the frame-start pose, reads the host transform as the requested target pose, sweeps between those poses, and clips the first static-style blocker. Dynamic targets crossed before the first blocker are woken and position-corrected through service-owned handoff queues. At a shape-exact contact already present at frame start, the target's outward surface normal decides whether motion is closing. Tangential or separating motion continues without publishing a false blocker or dynamic handoff. Discrete contact response samples the same prepared kinematic end velocity, so authored same-frame linear and angular motion contributes consistently even when the kinematic body was processed earlier in service order.

Dynamic Candidate Ordering

Prepare Geometry and Trajectories

Before frame preparation, body-owned colliders publish pending geometry through the normal shape transaction. Candidate bounds, inertia and mixed slab thickness therefore use the same committed geometry as subsequent motion samples. The published body proxy encloses the entire sampled rotation about the body's pose origin, including rounded attachments and compound leaves. This physical enclosure is separate from the supported geometry admission budget.

Moving-pair CCD uses immutable frame-start candidate indices plus bounded dirty overlays for bodies whose same-frame handoff changes their remaining swept bounds. A dirty body shadows its immutable entry; stale prepared bounds are not unioned back into admission. Each body exposes a canonical piecewise position, rotation, and velocity trajectory. Later sources therefore sample the exact pre-impact and post-impact history instead of whichever pose happened to be published most recently. Translational moving-pair reducers traverse only the target segments that overlap the source's remaining interval, clip the source sweep to each segment, and map segment-local hits back to the source's global time of impact.

Handoff boundaries are right-continuous: when a target reverses exactly at a shared boundary, the successor segment owns that instant. Because canonical segments are chronological and non-overlapping, the first admitted non-boundary hit is the global earliest hit. This contract is shared by dynamic and kinematic 2D, 3D, and mixed CCD.

Compare Hits Across Trajectories

Relative circle and sphere reducers keep motion as an endpoint-free direction plus physical distance. They compare the exact hit distance with the active overlap boundary, reconstruct both bodies from their authored trajectory segments, and only then materialize normalized time for arbitration. This avoids constructing an unrepresentable relative endpoint or collapsing distinct spatial contacts during early Q32.32 time conversion.

Mixed moving-pair admission encloses an embedded 2D shape with the ceiling-safe Euclidean combination of its planar pivot radius and slab half-thickness. That radial interval is geometry-only: exact reducers or sampled contact normals own closing-direction admission and candidate-speed ranking. A conservative proxy therefore cannot reject a real slab-closing contact merely because the proxy normal is separating, and it cannot promote an enclosing-proxy-only hit after an exact reducer certifies a miss.

Candidate results use time of impact and stable collider identity or dimension-tagged mixed keys. Cross-dimensional arbitration puts 2D first on an exact-time tie. The ordering is deterministic across repeated runs.

Continue After an Impact

An impact can change another body's motion while time remains in the step. The physics service queues that body to continue along its updated path. These handoffs let dense contact chains advance in a deterministic order.

Queue admission deduplicates a body only while it owns an unread entry. Dequeue releases that ownership before consumption, allowing a later same-frame relay to append the body again under the same deterministic iteration budget. Requeued work that exceeds the budget is explicitly discarded rather than left as stale continuation state. A later terminal handoff update (no remaining time or no resulting motion) likewise cancels any older pending continuation for that body; latest-state-wins includes the absence of further work.

Mixed CCD

Mixed CCD uses explicit mixed query reducers only in PhysicsRuntimeMode.Mixed. PhysicsRuntimeMode.Both advances 2D and 3D services side by side without cross-dimensional CCD.

3D swept-sphere mixed CCD routes through QueryMixed.SweepSphereAgainst2D. Circle slabs use the exact spherical dilation of their finite vertical cylinder, including rounded cap rims. Capsule slabs use an exact union of their expanded planar side and cap cores, four sphere-dilated straight rims, and two sphere-dilated vertical endpoint cylinders. Both reducers retain full-domain finite-axis arithmetic through the final distance and report Exact. AABB, convex polygon, and supported compound slab hits use their exact finite-slab reducers.

2D swept-circle mixed CCD routes through QueryMixed.SweepCircleAgainst3D. Supported primitive, mesh, and compound target families use exact reducers for the public mixed query contract. Rotated finite cones use the same support-mapped convex advancement kernel as 3D swept source queries with a query-owned circle-slab source.

PhysicsMixedHit.ReducerKind labels exact hits separately from conservative proxy candidates used by dynamic CCD paths.

Rotational CCD

When a Turn Needs a Sweep

A sphere or planar circle with an exactly zero collider-local offset occupies the same geometry while turning. Gravitas still applies its requested rotation and preserves angular state, but does not charge that turn as a geometric sweep. An offset round collider still sweeps about its body pivot. Nearby rotating obstacles can require rotational sampling even when the source is centered or stationary, including opposite-dimensional obstacles in Mixed mode.

For a centered round source already touching a supported convex primitive, tangential or separating motion does not become a rotational blocker merely because another nearby object is rotating. Closing motion is still tested. Compounds and concave targets retain conservative handling: a non-closing contact on one child is not proof that another child is clear.

For a non-compound source rotating solely around a cardinal supporting-plane axis, CCD can also certify tangential or separating motion against a stationary mesh or cuboid. Exact source support must start on or beyond the full target's supporting plane, and the source's quaternion and angular components must preserve that projection throughout the interval. Mesh targets include every vertex; compound targets include every mesh/cuboid leaf. A floor contact cannot hide another blocking part. General rotations, moving targets and curved target leaves retain the conservative interval search when this proof is unavailable.

Prove That an Interval Is Clear

Rotational CCD is bounded and deterministic across same-dimensional and mixed pairs. When either participant has rotational motion, source translation, source rotation, target translation, and target rotation compete in one normalized-time arbiter. It traverses intervals earliest-first for each candidate and samples both prepared poses at each midpoint. Shape-specific closest-feature separation, with a conservative AABB fallback where no tighter proof exists, certifies an interval only when its gap exceeds an outward-rounded bound on both participants' linear and pivot-centered angular travel. The bound also scales fixed-point pose uncertainty by pivot radius.

When aggregate bounds overlap, compound pairs must prove separation for every leaf pair. Concave meshes query their local triangle BVH with the other shape's midpoint enclosure expanded by the combined motion bound. An empty query proves separation; candidate triangles use exact finite box/triangle SAT. Cuboids and embedded 2D shapes retain an oriented enclosure, so a long rotating shape does not stop merely because its axis-aligned bounds cover an empty triangle corner. Pure 2D compounds and both mixed source directions use the same leaf-pair rule.

These certificates preserve conceptual mesh-local geometry when absolute world vertices are unavailable. Closed convex hull interiors, degenerate triangles, unrepresentable enclosure widths and capsule local extents that would clip before translation retain the unresolved result. An overlapping enclosure is not a contact witness and may still require conservative bounded refinement.

Mixed mesh/slab interval probes reuse exact finite-triangle admission without constructing contact rows. Standalone open or concave mesh/cone probes use the same split: exact finite admission during refinement, then the ordinary complete manifold at the accepted response pose. Declared mesh continuity and closed convex containment keep their existing complete-contact path.

Build Response at the Accepted Contact

A retained witness can lie after an earlier unresolved safe frontier. Complete response rows are built when the witness time equals that frontier; both source and moving target are resampled at the exact witness time before closing selection. Later geometric witnesses remain upper bounds and cannot authorize response at an earlier frontier. Mixed rotating kinematic sources against targets without solver mobility clamp from exact geometry and time alone. Dynamic response and translational fallback hit reporting retain complete rows. Conservative pure-rotation restarts reuse body-owned candidate buffers while the pivot and proxy bounds stay unchanged.

Any translation or response gathers fresh candidates; target validity, prepared trajectories and earliest-hit ordering are checked again on every restart. In both 2D and 3D, a live registry containing only the source collider needs no same-dimensional candidate query. The gatherer clears retained results; the separate mixed search still runs. Registering another collider resumes normal collection immediately.

Stop Safely When the Budget Runs Out

An unresolved interval is subdivided until a fixed depth or per-candidate work budget. A witnessed earliest contact can apply the contact-point response and bounded handoffs atomically. A later contact is not a response at an earlier unresolved boundary. If bounded refinement cannot advance that boundary, an admitted terminal clamp preserves dynamic momentum, retains a stationary trajectory for the rest of the frame, and reports the CCD limit when frame time remains. This also applies when no contact has been witnessed: uncertainty can require a safe stop, but does not justify an impulse or discarded angular motion.

Only the immediate prior pair is excluded from continuation, so a deterministic A -> B -> A same-frame chain remains admissible. Candidate results are ordered by normalized time, target dimension, and stable collider identity.

Trajectory mutation and dirty-overlay admission share a deterministic frame budget. If either participant cannot reserve all state required for an atomic pair update, Gravitas conservatively clamps before mutating either body and reports the CCD iteration limit. Linear-only handoffs preserve unrelated angular acceleration, and angular-only handoffs preserve unrelated linear acceleration.

Choose Rotational Candidates

Rotational broad-phase radii are measured from each body's actual rotation pivot, not merely from the collider center, so local offsets and remote compound parts remain inside the candidate volume. Unsupported collision pairs are skipped explicitly. If the required pivot radius exceeds the scalar domain, candidate admission scans the bounded context registry instead of issuing an effectively unbounded GridForge query. Dynamic and kinematic moving targets use their prepared piecewise trajectories; mixed candidates are admitted only in PhysicsRuntimeMode.Mixed, never in Both.

Diagnostics And Replay

Check these counters after LateSimulate() to see how much CCD work the step did and whether it reached a limit.

  • On SolidBody and SolidBody2D
    • LastContinuousCollisionToiIterationCount
    • LastContinuousCollisionToiIterationLimitReached
  • On GravitasPhysicsService and GravitasPhysics2DService
    • LastContinuousCollisionIslandCount
    • LastContinuousCollisionIslandIterationCount
    • LastContinuousCollisionIslandLimitReached

The body counters are deterministic frame-local state for tuning, tests, and host diagnostics. The service counters track CCD island and handoff work without adding event-buffer traffic to the hot path.

Active cross-frame CCD handoff state is included in the authoritative replay hash because it can affect the next fixed step. Rebuildable per-frame CCD snapshots are excluded from ordinary authoritative hashes and are available only through solver-cache hash mode when useful for drift RCA.

Rules That Matter

  • Keep CCD target filters separate from public query filters.
  • Keep exact reducers and conservative proxy behavior explicit.
  • Bound TOI iterations and handoff processing.
  • Preserve stable candidate ordering.
  • Use mixed CCD only through the mixed runtime path.
  • Add replay tests for any CCD state that affects continuation.
  • Add benchmarks for dense dynamic, mixed, rotational, or kinematic-source CCD changes.

Source Map