# Dynamic Gravity: Usage & Setup Guide

#### **What Dynamic Gravity Does**

Dynamic gravity continuously probes the environment to align gravity with nearby surfaces.

* Gravity direction is derived from multi-directional collision probes
* Updates every frame using head, movement, and feet detection
* Supports walls, ceilings, and arbitrary shapes
* Predictive ceiling catch when jumping toward overhead surfaces
* Optional predictive wall and ledge gravity transitions via Surface Forward Probe (`bUsePredictiveProbes`)
* Intended for complex geometry traversal
* Fully server-authoritative and replicated
* High-Precision Support: Supports double-precision math (`FVector3d`) to ensure stability and eliminate "splitting" jitter at large world distances.

***

#### **Required Setup**

**1. Character Setup**

Your character must use `UGravityMovementComponent`.

* Replace `CharacterMovementComponent` with `GravityMovementComponent`
* Replication must be enabled (default in constructor)
* Works with standard `ACharacter`

**2. Collision Channel Setup**

Configure the dynamic gravity trace channel:

```
DynamicGravityTraceChannel = ECC_GameTraceChannel1; // Example
```

This channel must be set up in your project settings to respond to world geometry.

**3. Enable Dynamic Gravity (Server Only)**

```
GravityMovementComponent->SetGravityMode(EEffectiveGravityMode::Dynamic);
```

* This must be called from a server-replicated function
* Client calls are ignored
* Server computes gravity direction
* Resulting direction and rotation replicate to clients

***

#### **How Gravity Direction Is Determined**

Dynamic gravity uses three simultaneous probe systems by default. A fourth is available as an opt-in.

**Head Probe (Ceiling Detection)**

* Sphere sweep from 50 units above character, extending 30 units upward
* Radius: 20 units
* Detects overhead surfaces when jumping
* When hit while airborne: commits gravity toward ceiling and starts fallback timer
* Velocity is re-projected to prevent launch kick on gravity commit

**Movement Probes (Wall Detection)**

* Four diagonal sweeps in cardinal directions with upward bias
* Distance: 25 units per direction
* Radius: 25 units
* Detects approaching walls during movement
* Skipped when head proposal is active

**Feet Probe (Ground Detection)**

* Two-stage system: sphere sweep anchor probe followed by fixed low-profile capsule confirmation at the anchor point
* Anchor probe traces downward from 40 units below actor origin up to `LatchDistance`
* Tracks raw unsmoothed gravity direction for improved precision on curved and rotating surfaces
* For rotating movable bases, uses a local-space swivel — last valid hit is cached in component space and reconstructed in world space each frame to track the surface
* Skipped during active head steering transitions (`AlignDot < 0.985`)

**Surface Forward Probe (Wall & Ledge Classification) — Opt-In**

* Disabled by default — enable via `bUsePredictiveProbes`
* Runs only when grounded and feet probe is active
* Dual wall probes (low and high) sweep forward using velocity-derived direction with a hold buffer after stopping
* Ledge drop probe sweeps downward ahead of the character to detect surface edges
* Full hysteresis system for both wall entry and exit — eliminates flicker on curved geometry
* Drives dedicated wall and ledge rotation branches with independent tunable lerp speeds
* `WallProbeDistance`, `LedgeProbeDistance`, and `LedgeProbeLength` are all tunable

**Probe Priority**

* Head (highest priority when airborne with no active goal direction)
* Movement (secondary)
* Feet (tertiary, suppressed during active head steering)
* Surface Forward Probe drives wall/ledge rotation branches independently when `bUsePredictiveProbes` is enabled
* If `DynamicGoalDir` is active and airborne: goal direction takes full priority
* If no probes hit: falls back to `FallBackDir` (default: 0,0,-1)

***

#### **Rotation Behavior**

* High-Precision Math: When `bUseHighPrecisionMath` is enabled, all probe calculations use `FVector3d`. The system treats the character as a temporary origin for these traces, ensuring maximum directional accuracy regardless of world position.

**Default Rotation**

Character rotates so its down axis aligns with the probe-detected direction.

* Rotation is smooth and incremental
* Head-probe transition: quaternion stepping using `DynamicHeadTransitionRotationSpeed`
* Surface smoothing: lerp using `DynamicSurfaceLerpSpeed`
* Wall branch: lerp using `DynamicWallLerpSpeed` — only active when `bUsePredictiveProbes` is enabled
* Ledge branch: lerp using `DynamicLedgeLerpSpeed` — only active when `bUsePredictiveProbes` is enabled
* Enhanced two-stage smoothing available via `bUseEnhancedSmoothing` — absorbs polygon face noise on curved surfaces, first stage speed controlled by `DynamicEnhancedSurfaceSmoothingSpeed`
* Per-frame rotation is clamped to the relevant speed property per branch

**Flying Mode**

* If `bApplyGravityRotationWhileFlying` is false (default), gravity rotation is skipped and only `GravityDirCached` is updated
* If `bApplyGravityRotationWhileFlying` is true, the character smoothly aligns its rotation to the active gravity direction while flying
* On transition out of flying mode, the cached direction resyncs from actual rotation to prevent snapping

**Rotation Constraints (Optional)**

```
SetGravityRotationMode(EGravityRotationMode::Default);
SetGravityRotationMode(EGravityRotationMode::ForwardBack);
SetGravityRotationMode(EGravityRotationMode::LeftRight);
```

Used to restrict how rotation is applied when transitioning between surfaces.

***

#### **Moving Bases (Critical)**

**Important Limitation**

Unreal does not replicate arbitrary base rotation for non-Z gravity. This can cause:

* Client visual drift
* Z-down fallback on listen servers

**Solution**

If walking on movable or rotating surfaces:

```
bApplyReplicatedRotationOnMovingBases = true;
```

This applies replicated base rotation correction, affects visuals only, and does not alter physics or collision.

To ignore base rotation entirely:

```
bIgnoreBaseRotation = true;
```

***

#### **Networking & Replication**

* Gravity mode is replicated
* Gravity direction is computed server-side from probe results
* Rotation is predicted and smoothed client-side
* Simulated proxies receive correction in tick
* Authority enforced for all gravity changes

***

#### **Blueprint Usage (Server-Authoritative)**

**Minimal Blueprint Flow**

1. Detect overlap or surface contact
2. Call a Server RPC — gravity changes must execute on the server
3. Inside the Server Function: Get `GravityMovementComponent`, call `SetGravityMode(EEffectiveGravityMode::Dynamic)`
4. Configure `DynamicGravityTraceChannel` in details panel or constructor

**Optional (Server Only)**

* Set rotation constraints via `SetGravityRotationMode`
* Enable moving-base replication fixes via `bApplyReplicatedRotationOnMovingBases`
* Enable predictive surface probes via `bUsePredictiveProbes`

***

#### **Configuration Properties**

*Probe Behavior*

```
bUseHighPrecisionMath             // Enables double-precision calculations for large-scale stability.
DynamicGravityTraceChannel        // Collision channel for all probes
LatchDistance                     // Max feet probe latch distance (default: UE_LARGE_WORLD_MAX)
FloorDetectionTolerance           // Fallback safety net distance (default: 100.0)
bUsePredictiveProbes              // Enables Surface Forward Probe system (default: false)
WallProbeDistance                 // Forward reach of wall detection probes (default: 75.0) — requires bUsePredictiveProbes
LedgeProbeDistance                // Forward reach of ledge drop probe (default: 75.0) — requires bUsePredictiveProbes
LedgeProbeLength                  // Downward reach of ledge drop probe (default: 55.0) — requires bUsePredictiveProbes
```

*Rotation Settings*

```
DynamicHeadTransitionRotationSpeed   // Quat step speed for head-probe transitions (default: 180.0)
DynamicSurfaceLerpSpeed              // Lerp speed for surface following (default: 15.0)
DynamicWallLerpSpeed                 // Lerp speed for wall transitions (default: 25.0) — requires bUsePredictiveProbes
DynamicLedgeLerpSpeed                // Lerp speed for ledge transitions (default: 25.0) — requires bUsePredictiveProbes
DynamicEnhancedSurfaceSmoothingSpeed // First-stage lerp speed for enhanced smoothing (default: 10.0)
bUseEnhancedSmoothing                // Enables two-stage surface smoothing (default: false)
RotationStopTolerance                // Snap threshold angle, 0..1 normalized (default: 0.08)
```

*Fallback Settings*

```
FallBackDir      // Direction when no surface found (default: 0,0,-1)
FallBackTimer    // Seconds before reverting from ceiling catch (default: 1.0)
```

*Flying*

```
bApplyGravityRotationWhileFlying  // Whether to align rotation to gravity while flying (default: false)
```

*Moving Base*

```
bApplyReplicatedRotationOnMovingBases  // Sync simulated proxy rotation on movable bases (default: false)
```

***

#### **Debug Visualization**

Enable with `bShowVisualDebugs` = true (development builds only)

* Red sphere: Head probe (hit/miss)
* Green spheres: Movement probes (4 directions)
* Blue line + capsule: Feet probe anchor and confirmation sweep
* Orange line + sphere: Low wall forward probe hit (requires `bUsePredictiveProbes`)
* Cyan line + sphere: High wall forward probe hit (requires `bUsePredictiveProbes`)
* Yellow/Green line: Ledge drop probe — yellow = ledge detected, green = floor continues (requires `bUsePredictiveProbes`)
* Yellow line + sphere: Final selected gravity direction
* Debug widget: Real-time readout of gravity state, rotation mode, latch status, latch distance, and floor detection — displayed per client and server character

***

#### **Performance Notes**

Per-frame collision cost when active:

* Grounded (default): 2 checks (anchor sphere + capsule confirmation)
* Grounded (`bUsePredictiveProbes` enabled): up to 5 checks (anchor sphere + capsule confirmation + up to 3 forward probe sweeps)
* Airborne with head proposal active: 1 check (head sphere only, movement and feet skip)
* Airborne standard: up to 7 checks (head + 4 movement + anchor + capsule)

Optimization:

* Configure `DynamicGravityTraceChannel` with minimal responders
* Movement probes early-out after first hit
* Movement probes and feet confirmation skip during head steering transitions
* Surface Forward Probe only runs when grounded, feet probe is active, and `bUsePredictiveProbes` is enabled

***

#### **Summary**

* Dynamic gravity uses multi-probe collision detection
* v2.4.3 Feature: High-precision math ensures stability at extreme world distances.
* Handles grounded and airborne surface transitions
* Supports ceiling catch and wall detection by default
* Surface Forward Probe (opt-in via `bUsePredictiveProbes`) drives smooth wall and ledge transitions with full hysteresis
* Rotating platform support via local-space swivel system
* Enhanced two-stage surface smoothing available for curved geometry
* `bApplyGravityRotationWhileFlying` supported
* Requires collision channel configuration
* Requires opt-in base rotation replication for movable geometry
* Fully authoritative, replicated, and deterministic


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://replicated-gravity.gitbook.io/replicated-gravity-docs/getting-started/setup-guides-and-tutorials/dynamic-gravity-usage-and-setup-guide.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
