Technical Documentation

Complete technical reference for the VoxelPlayerController system

Search across all 44 pages of documentation

Project Overview

The VoxelPlayerController is a comprehensive Unity character controller system that provides modular, decoupled gameplay systems for player movement, combat, environment interaction, and AI.

Core Architectural Philosophy

  • Modularity: Each script handles a specific, well-defined responsibility
  • Separation of Concerns: Systems are decoupled and communicate through clearly defined interfaces
  • Dual Input System Support: Both Legacy Input System and New Input System are supported simultaneously
  • Centralized Audio Management: All audio playback is routed through a single controller
  • Environment-Aware Systems: Systems intelligently respond to environmental conditions (water, obstacles, slopes)

System Interaction Map

PlayerInput Manager
PlayerController
PlayerCamera
PlayerDamage
PlayerAudio
HealthSystem

Architecture

The system follows a strict separation of responsibilities principle with nine distinct layers:

1

Input Layer

PlayerInputManager abstracts all input processing across both Legacy and New Input Systems

2

Movement Automation Layer

Automatic Sprint System provides threshold-based automatic running without additional key presses, while maintaining manual control priority

3

Movement Layer

PlayerController handles locomotion, physics, and state management (Idle, Walk, Run, Crouch, Jump, Dash)

4

Environmental Layer

PlayerEnvironmentSensor and WaterSwimming handle terrain analysis, obstacle detection, and water interactions

5

Combat Layer

PlayerDamage manages weapon systems, melee attacks, and hit detection

6

Health Layer

HealthSystem manages damage, death sequences, respawn logic, and health regeneration

7

Visual Layer

PlayerCamera and EffectSystem handle first-person/third-person views and visual effects

8

Audio Layer

PlayerAudioController centralizes all sound playback across five dedicated AudioSources

9

AI Layer

AdvancedNPC provides state-driven enemy behavior with NavMesh navigation

9

Debug Layer

PlayerDebugDisplay provides runtime visual feedback for input controls

Why This Architecture Avoids Tight Coupling

  • Interface-Based Communication: Systems expose clean public APIs instead of internal state manipulation
  • Event-Driven Updates: Health changes and state transitions use delegate patterns
  • Dependency Injection: Required components are cached but not hard-referenced
  • Fallback Systems: Missing components trigger graceful degradation
  • Input Abstraction: Complete separation between input detection and gameplay response

Core Systems Documentation

PlayerController.cs

Movement Core System

IS Responsible For:

  • Character movement (walking, running, crouching, jumping)
  • Physics-based collision response and ground detection
  • Procedural animation for limbs and body
  • State management for movement modes
  • Camera-relative movement calculation
  • Input processing for movement-related actions

IS NOT Responsible For:

  • Camera control (delegated to PlayerCamera)
  • Combat logic (delegated to PlayerDamage)
  • Water interactions (delegated to WaterSwimming)
  • Audio playback (delegated to PlayerAudioController)
  • Input device detection (delegated to PlayerInputManager)
Dependencies
Required Components:
- Rigidbody (for physics)
- CapsuleCollider (for collision)
- PlayerEnvironmentSensor (ground/obstacle detection)
- PlayerCamera (camera-relative movement)

Optional Components:
- PlayerAudioController (footstep sounds)
- WaterSwimming (water state awareness)
- PlayerInputManager (input abstraction)

PlayerDamage.cs

Combat Melee

IS Responsible For:

  • Weapon inventory management and switching
  • Melee attack execution and cooldown timing
  • Enemy hit detection using sphere casts
  • Damage application to AdvancedNPC entities
  • Weapon equip/unequip animations and positioning
  • Attack point management based on equipped weapon

IS NOT Responsible For:

  • Player health management (delegated to HealthSystem)
  • Ranged combat (outside current scope)
  • Enemy AI behavior (delegated to AdvancedNPC)
  • Audio playback (delegated to PlayerAudioController)
  • Input processing (delegated to PlayerInputManager)

Attack Execution Flow

  1. Input validation (cooldown, water state, equipment state)
  2. Sphere cast from attack point within configured range and angle
  3. Enemy validation (IsAlive, IsDying checks)
  4. Damage application via AdvancedNPC.TakeDamage()
  5. Visual/audio feedback through effects and PlayerAudioController

PlayerEnvironmentSensor.cs

Detection Terrain

Pure detection system - never modifies physics, movement, or gameplay state, only provides detection results for other systems to act upon.

Key Public Properties (All Read-Only)
IsFrontBlocked / IsBackBlocked / IsLeftBlocked / IsRightBlocked
GroundNormal - Current ground surface normal
SlopeAngle - Ground slope in degrees
FrontObstacleDistance / etc. - Exact obstacle distances
StepHeight / StepSmooth - Auto-step configuration access

PlayerCamera.cs

Camera View

View Management

  • First-person: Positioned at player's head with crosshair
  • Third-person: Orbital camera with collision avoidance
  • Switching: Smooth transition between view modes
  • Water adaptation: Automatic view adjustments in water
Execution Order Criticality
1. Update() - Handles input and state changes
2. LateUpdate() - Updates camera position (after player movement)
3. Water state checks before position calculation
4. View switching uses coroutines for smooth transitions

WaterSwimming.cs

Swimming Physics

Swimming Activation Flow

  1. Chest submersion with time buffer triggers swimming
  2. Disables PlayerController, enables swimming physics
  3. Applies water drag and buoyancy forces
  4. Initializes swim direction from camera

PlayerAudioController.cs

Audio Sound

Centralized audio management with five dedicated AudioSources for domain separation:

Land Sounds

Steps, jumps, landings, crouches, dashes

Water Sounds

Splashes, swimming loops

Melee Sounds

Swings, hits, equip/unequip

Damage Sounds

Damage taken, death

Health Sounds

Healing, regeneration (reserved)

HealthSystem.cs

Health Damage

Death Sequence Flow

  1. PlayerController and Camera disabling
  2. Physics reconfiguration for ragdoll-like behavior
  3. Visual effects and death sound playback
  4. Death animation coroutine
  5. Respawn timer initiation

AdvancedNPC.cs

AI Navigation

AI State Machine

Idle → Patrol
Patrol → Chase
Chase → Attack
Attack → Return
Return → Idle

PlayerInputManager.cs

Input Controls

Unified input abstraction supporting both Legacy and New Input Systems simultaneously.

Key Public Getters
GetMoveInput() - 2D movement vector
GetLookInput() - 2D look input with sensitivity
GetJumpInput() / GetSprintInput() / GetCrouchInput()
GetAttackInput() / GetMeleelInput() - Combat triggers
GetDashInput() / GetInteractInput() - Special actions
GetEquipWeaponInput() / GetSwitchWeaponInput()
GetSwitchViewInput() / GetRespawnInput()

Automatic Sprint System

Movement Automation

IS Responsible For:

  • Automatic transition to Run state when input exceeds threshold
  • Monitoring movement input magnitude continuously
  • Maintaining compatibility with manual sprint system
  • Preventing activation during incompatible states (crouch, dash, airborne)
  • Providing configurable activation thresholds via Inspector

IS NOT Responsible For:

  • Manual sprint input processing (delegated to PlayerInputManager)
  • Movement physics (delegated to PlayerController)
  • Input device detection (delegated to PlayerInputManager)
  • Animation state management (informed but not controlled)
  • Audio feedback for sprinting (delegated to PlayerAudioController)
Configuration Parameters (Inspector)
autoSprintEnabled: bool - Enable/disable the automatic sprint system
                        autoSprintThreshold: float (0.6–0.9) - Activation threshold percentage
                                        Default: 0.8 (80% of maximum input)

                        Manual sprint always takes priority over automatic sprint.
                        System only activates when grounded and in walk/run states.

State Transition Logic

  1. Input Monitoring: Continuously tracks movement input magnitude
  2. Threshold Check: When magnitude > autoSprintThreshold → Run state
  3. Priority Check: Manual sprint input overrides automatic system
  4. State Validation: Only activates if grounded and not crouching/dashing
  5. Deactivation: When input < 0.5 and no manual sprint → Walk state

API Reference

System Key Methods Key Properties
PlayerController State queries for external systems IsGrounded, currentState, limb transforms
Automatic Sprint System UpdateAutoSprint(), IsAutoSprintActive() autoSprintEnabled, autoSprintThreshold, IsSprintingAuto
PlayerDamage TryAttack(), ToggleWeapon(), SwitchWeapon() IsWeaponEquipped, CurrentWeapon, IsWeaponMoving
HealthSystem TakeDamage(), Heal(), Die(), Respawn() IsAlive, IsDying, currentHealth, maxHealth
AdvancedNPC TakeDamage(), SetState(), ResetNPC() currentState, IsAlive, currentHealth
PlayerInputManager All Get[Action]Input() methods IsInputEnabled, IsUsingGamepad

Public API Design Principles

  • Clean Interfaces: Each system exposes minimal, focused public methods
  • Event-Driven: Health changes, state transitions use delegate patterns
  • Read-Only Properties: Sensor data and state queries are read-only
  • Consistent Naming: Get[Action]Input() pattern across all input methods
  • Null Safety: All public methods handle missing dependencies gracefully

Workflow & Setup

1

Import & Setup

Import the asset package into Unity 2020.3 LTS or newer. Add the player prefab to your scene.

2

Configure Environment

Set up layer masks for ground, water, and obstacles. Configure NavMesh for NPC AI if using AdvancedNPC system.

3

Input System Selection

The system automatically detects available input systems. Configure InputActionAsset for New Input System or use Legacy bindings.

4

Customize Parameters

Adjust movement speeds, camera settings, combat parameters, and audio volumes through Inspector.

5

Test & Iterate

Press Play. The system supports immediate testing with all components pre-wired. Modify parameters in real-time.

Plug-and-Play Philosophy

The architecture supports a "create a level and play" workflow suitable for rapid prototyping and production. Core prefabs are provided with all components pre-wired. Configuration is primarily Inspector-driven with sensible defaults.

Performance Optimization

Cooldown Systems

Environment detection uses configurable cooldowns (default: 0.1s for obstacle checks) to prevent per-frame performance spikes.

Optimization Radii

Water detection ignores distant water bodies. NPC activation uses squared distance calculations for efficiency.

Pre-allocation

Audio uses five dedicated AudioSources created at startup to prevent runtime allocation. Coroutine management prevents memory leaks.

Execution Order

Strict separation: Input in Update, physics in FixedUpdate, camera in LateUpdate. Prevents frame spikes and ensures smooth rendering.

Automatic Sprint Optimization

Efficient input magnitude monitoring with threshold-based state changes. Minimal performance overhead as it leverages existing input polling and state machine infrastructure.

Performance-Critical Design Decisions
// EnvironmentSensor.cs - Obstacle check cooldown
private float lastObstacleCheck;
public float obstacleCheckCooldown = 0.1f;

// WaterSwimming.cs - Distant water ignoring
public float activationRadius = 20f;

// AdvancedNPC.cs - Squared distance for activation
private float activationRadiusSquared;

// PlayerAudioController.cs - Pre-allocated AudioSources
private AudioSource landAudio, waterAudio, meleeAudio, damageAudio, healthAudio;