Files
UE5-Modular-Game-Framework/docs/developer/03-interaction-systems.md
Lefteris Notas 8bc731e5ae feat: Add multiplayer networking architecture and documentation updates
- Updated Master Blueprint Index to include Multiplayer Networking support.
- Added detailed Multiplayer Networking sections across all developer documentation (01-11).
- Introduced authority maps, key patterns, and RPC guidelines for each system.
- Established a comprehensive multiplayer networking architecture document outlining core principles, replication strategies, and anti-cheat considerations.
- Enhanced UI documentation to clarify local-only behavior and binding to replicated dispatchers.
- Implemented client prediction strategies and RPC naming conventions for consistency across the framework.
2026-05-19 17:15:57 +03:00

272 lines
14 KiB
Markdown

# 03 — Interaction & World Manipulation Systems (Systems 16-23)
**Category Purpose:** These 8 systems handle everything the player can do with the world — detecting interactable objects, opening doors, solving puzzles, traversing obstacles, dragging physics objects, using world devices (levers, buttons), viewing diegetic displays, and finding hiding spots. The `BPC_InteractionDetector` is the central hub; all other systems respond to its dispatchers or interface calls.
---
## System Index
| # | System | Asset Type | Role |
|---|--------|-----------|------|
| 16 | `BPC_InteractionDetector` | Component | Raycast interaction detection hub; holds/press/double-tap |
| 17 | `I_HidingSpot` | Interface | Interface for hideable world objects |
| 18 | `BPC_DiegeticDisplay` | Component | In-world screens (wristwatch, monitors, holograms) |
| 19 | `BP_DoorActor` | Actor | Physical door: 6-state machine, lock/barricade/key |
| 20 | `BP_PuzzleDeviceActor` | Actor | Puzzle device base: state machine, solution checking |
| 21 | `BPC_ContextualTraversalSystem` | Component | Vault/mantle/slide/squeeze via Motion Warping |
| 22 | `BPC_PhysicsDragSystem` | Component | Grab/drag/release physics objects |
| 23 | `BPC_UsableWorldObjectSystem` | Component | Generic world objects: levers, valves, buttons, panels |
---
## Category Data Flow
```
┌────────────────────────────────────────────────────────────────────┐
│ INTERACTION FLOW │
│ │
│ BPC_InteractionDetector (runs on player) │
│ │ Timer-based sphere trace every 0.1s │
│ │ Filters by: I_Interactable interface │
│ │ Sorts by: Priority (Emergency > High > Normal > Low) │
│ │ then Distance (closest wins) │
│ ├─► OnTargetFound → WBP_InteractionPromptDisplay (show prompt) │
│ │ │
│ │ On player input: │
│ ├─► Press: immediate interaction │
│ ├─► Hold: radial progress fill → interaction on complete │
│ └─► DoubleTap: two rapid presses │
│ │
│ Target types are routed: │
│ ├─► BP_DoorActor.Interact_Implementation → door logic │
│ ├─► BP_PuzzleDeviceActor.Interact_Implementation → puzzle │
│ ├─► BP_ItemPickup.Interact_Implementation → inventory add │
│ ├─► BP_ContainerInventory.Interact_Implementation → container │
│ ├─► BP_UsableWorldObject.Interact_Implementation → lever/etc. │
│ └─► I_HidingSpot → BPC_HidingSystem.EnterHideSpot() │
│ │
│ Independent systems (not through InteractionDetector): │
│ ├─► BPC_ContextualTraversalSystem (movement-based, auto-detect) │
│ └─► BPC_PhysicsDragSystem (grab input, physics constraint) │
└────────────────────────────────────────────────────────────────────┘
```
---
## 16 — BPC_InteractionDetector: The Interaction Hub
**What It Does:** The player's "interaction eye" — performs continuous sphere traces forward from the camera, detects all `I_Interactable` actors within range, sorts them by priority and distance, selects the best target, and manages the interaction prompt UI. Every interactive object in the game funnels through this component.
**How It Works Internally:**
**Detection Loop:**
- Timer fires every `ScanInterval` (default 0.1s)
- Sphere trace forward: `InteractionRange` (default 250cm), `DetectionAngle` cone, `TraceRadius` sphere
- Each hit actor checked for `I_Interactable` implementation
- Duplicates removed, sorted by `Priority` descending then `Distance` ascending
- Clamped to `MaxTargetsInRange` (default 16)
- `DetectionState` tracks: NoTarget → TargetInRange → TargetConfirmed → Interacting
**Input Modes:**
- `Press`: Single press to interact (standard)
- `Hold`: Hold button for `HoldDuration` seconds with progress bar
- `DoubleTap`: Two rapid presses within threshold
- `Auto`: Triggers on proximity without input
**Interaction Protocol:**
1. Player presses interact → `OnInputInteractPressed`
2. If `DetectionState >= TargetConfirmed` and input mode matches:
- Press mode: calls `PerformInteraction(Press)` immediately
- Hold mode: starts hold timer, fires `OnHoldProgressUpdated` each tick (for radial UI fill)
- DoubleTap mode: waits for second press within window
3. `PerformInteraction` sets `bIsPerformingInteraction = true`, calls `CurrentTarget.InterfaceRef.ExecuteInteraction(Instigator)`
4. Waits for interaction completion or timeout
5. On completion/cancel: resumes scanning
**Blocking Conditions:**
- During death (`bBlockDuringDeath`): interaction blocked
- While hidden (`bBlockDuringHiding`): blocked (player is inside a locker)
- During combat (`bBlockDuringCombat`): optionally blocked
- While already interacting (`bIsPerformingInteraction`): blocked (no double-interact)
**Target Scoring:**
- `CalculateInteractionScore()`: `Score = Priority * 100 - Distance * 0.5`
- Facing bonus: if camera angle to target < 15°, add 50
- Best target = highest score within range
**Implementation Patterns:**
- Trace pauses while interacting, resumes after completion
- `ForceSetTarget(Actor)` for scripted interactions (cutscene buttons)
- Highlight effect applied to current target via `I_Interactable.SetHighlighted()`
- Enter/exit tracking: fires `OnTargetEntered`/`OnTargetExited` when actors enter/leave range
**Integration Points:**
- **Broadcasts:** `OnTargetFound/Lost`, `OnInteractionStarted/Completed/Cancelled/Error`, `OnHoldProgressUpdated`
- **Calls:** `I_Interactable.ExecuteInteraction()` on target, `I_Interactable.SetHighlighted()`
- **Listens to:** `BPC_MovementStateSystem.OnPostureChanged`, `BPC_HealthSystem.OnDeathStateChanged`
---
## 17 — I_HidingSpot: Hiding Spot Interface
**What It Does:** Interface that all hideable world objects must implement. Provides slot management, entry/exit transforms, peek capability, and type classification.
**Key Functions:**
- `GetHideSpotInfo()` returns `S_HideSpotInfo` (type, slots, peek sockets, exit location, tags)
- `HasAvailableSlots()` boolean for occupancy check
- `OnPlayerEntered(Player)` / `OnPlayerExited(Player)` notify on occupancy change
- `GetEntryAnimation()` / `GetExitAnimation()` animation montages for smooth transitions
- `IsDetectableFrom(EnemyLocation)` LOS check helper
**Implementation:** Actors like lockers, wardrobes, beds, tall grass volumes, and shadow volumes implement this interface. The `BPC_HidingSystem` calls these functions to manage hide state.
---
## 18 — BPC_DiegeticDisplay: In-World Screens
**What It Does:** Manages in-world display surfaces the player's wristwatch UI, computer monitors, holographic projectors, and security camera feeds. These are diegetic (exist in the game world) rather than screen-space UI.
**Key Features:**
- Renders widget blueprints onto world-space surfaces via `WidgetComponent`
- Supports multiple display types: wristwatch, monitor, hologram, projection
- Screen power states: on/off/damaged/static
- Distortion effects for damaged screens
- Interaction-based activation (press E on monitor to view)
---
## 19 — BP_DoorActor: Physical Door System
**What It Does:** Powers all door-like actors hinged doors, sliding doors, double doors, roll-up doors, and trap doors. Manages a 6-state machine with lock/key mechanics, barricade health, one-way passage, auto-close, and puzzle-linked unlocking.
**State Machine:**
```
Closed → Opening → Open → Closing → Closed
↑ ↓
Locked ← (unlock transitions to Closed)
Barricaded → (break) → Closed
```
**Lock Types:** Unlocked, KeyRequired (specific key item), ItemRequired (crowbar/code), PuzzleLinked (external puzzle), Breachable (force/weapon)
**Animation System:**
- Uses Timeline to interpolate door rotation (hinged) or translation (sliding) from 0OpenAngle
- `OpenSpeed` and `CloseSpeed` control animation rate
- `AutoCloseDelay` starts timer after open; resets on re-open
- `LinkedActors` array notified on open/close (lights, alarms, traps)
**Implementation Patterns:**
- Implements `I_Interactable` called by InteractionDetector
- `TryUnlockWithItem()` queries `BPC_InventorySystem` for required key
- `DamageBarricade()` reduces health, broadcasts `OnBarricadeBroken` at 0
- `ForceSetState()` for save/load restoration bypasses animation
- One-way doors track which side was opened from (`bIsOpenFromFront`)
**Integration Points:**
- **Called by:** `BPC_InteractionDetector` (interact)
- **Queries:** `BPC_InventorySystem` (key check)
- **Notifies:** `LinkedActors`, AI perception (pathfinding update), AudioManager (door sounds), Save System
---
## 20 — BP_PuzzleDeviceActor: Puzzle Device Base
**What It Does:** Base class for puzzle devices combination locks, pressure plate sequences, symbol matching, pipe routing, and any interactive puzzle. Manages a state machine, validates solutions, and provides hints and rewards.
**Features:**
- State machine: Idle Active Solved Failed
- Solution checking against `DA_PuzzleData` Data Asset
- Hint system with configurable hint count and cooldown
- Reward dispatching on solve (item grant, door unlock, narrative flag set)
- Linked actor notifications (unlock connected door, activate machine)
- Timer-based puzzles with configurable countdown
---
## 21 — BPC_ContextualTraversalSystem: Vaulting & Climbing
**What It Does:** Handles player traversal of environmental obstacles using UE5 Motion Warping. Detects traversable surfaces (low walls, ledges, gaps, barriers) and plays root motion traversal montages with precise target alignment.
**Traversal Types:** Vault (low obstacles), Mantle (ledges), Slide (under barriers), Squeeze (narrow gaps), LedgeGrab (hang from ledges)
**Detection:**
- Forward capsule trace at waist, chest, and head heights
- Classifies obstacles by height: Low (step up), Medium (vault), High (mantle)
- Cooldown between traversals prevents animation spam
**Motion Warping:**
- Calculates exact target location for landing
- Warps root motion to hit target precisely
- `bIsTraversing` flag blocks input and other actions during animation
---
## 22 — BPC_PhysicsDragSystem: Object Grabbing
**What It Does:** Enables the player to grab, drag, and release physics-simulated objects. Uses physics constraints for smooth dragging and supports throw mechanics.
**Features:**
- Grab detection via line trace from camera
- Physics constraint attaches object to player's "hold position"
- Rotation control while held (mouse wheel or gamepad)
- Throw with configurable force on release
- Weight limit: heavier objects require more time to lift
- Works with `I_Holdable` interface for puzzle-specific objects
---
## 23 — BPC_UsableWorldObjectSystem: Generic World Devices
**What It Does:** Provides a generic interaction system for world objects that don't fit into door/puzzle/pickup categories levers, valves, buttons, switches, panels, dials, and crank handles.
**Features:**
- Implements `I_Interactable`, `I_Toggleable`, and `I_Adjustable` interfaces
- Binary devices (levers, buttons): toggle on/off
- Analog devices (valves, dials): continuous adjustment via mouse wheel or hold-and-drag
- Linked actor notifications: pulling a lever opens a gate elsewhere
- Animation playback with configurable duration
- State persistence via `I_Persistable`
---
## Common Implementation Patterns in This Category
1. **Interface-Driven Detection:** `BPC_InteractionDetector` doesn't know about doors, pickups, or puzzles it only checks for `I_Interactable`. Any new interactable just implements the interface.
2. **Priority Sorting:** Emergency targets (hide spots in combat) always selected over Low priority (ambient items).
3. **State Machines on Actors:** Doors, puzzles, and devices all use discrete state machines exposed via dispatchers never polling.
4. **Linked Actor Pattern:** Doors/puzzles/devices can notify other actors (lights, traps, doors) on state change via `LinkedActors` array.
5. **Input Mode Variety:** Press for quick actions, Hold for deliberate actions (pick lock, solve puzzle), DoubleTap for rapid actions.
6. **Save-Aware:** All interactive objects implement `I_Persistable` for state restoration.
---
## Multiplayer Networking
### Category Authority Map
| System | Authority | Client Request Pattern |
|--------|-----------|----------------------|
| `BPC_InteractionDetector` | Detection runs locally; interaction validated by server | `Server_PerformInteraction` RPC |
| `BP_DoorActor` | Server-authoritative state machine | `Server_Interact` server validates OnRep animates |
| `BP_PuzzleDeviceActor` | Server-authoritative | `Server_TrySolution` RPC |
| `BPC_ContextualTraversalSystem` | Client-predicted movement | Server validates traversal target |
| `BPC_PhysicsDragSystem` | Client-predicted physics | Server periodically corrects position |
| `BPC_UsableWorldObjectSystem` | Server-authoritative toggle/adjust | `Server_Use` RPC |
### Interaction Flow (Multiplayer)
```
Client looks at door → local trace detects it → shows "Press E"
Client presses E → calls Server_Interact(DoorActor)
Server: validates range, door state, lock
→ If valid: door state changes → RepNotify broadcasts
→ All clients: OnRep plays door animation
→ If locked: server rejects, Client_ShowError RPC to requesting client
```
### Full Spec
See [`docs/architecture/multiplayer-networking.md`](../architecture/multiplayer-networking.md) Section 3.3.
---
*Developer Reference v1.0 — 03 Interaction Systems. Companion to docs/blueprints/03-interaction/ specs.*