Bevy All-in-One Documentation

A powerful 3D/2.5D game controller plugin for Bevy Engine.


Project maintained by yaskhan Hosted on GitHub Pages — Theme by mattgraham

Player System Documentation

Table of Contents

  1. Overview
  2. Architecture & Core Concepts
  3. System Components
  4. Advanced Features
  5. System Integration
  6. Usage Patterns
  7. Best Practices
  8. Common Patterns
  9. Troubleshooting
  10. Performance Considerations
  11. Future Enhancements

Overview

The Player System is a comprehensive collection of plugins and components that manage all aspects of player character behavior, movement, and state management within the Bevy All-in-One Controller framework. This system provides a modular architecture that allows developers to implement complex player mechanics ranging from basic movement to advanced features like ragdolling, flying, swimming, and AI-controlled sequences.

The Player System consists of multiple interconnected subsystems that work together to provide a complete player character framework. Each subsystem is designed to be independently configurable while maintaining seamless integration with other systems throughout the game framework.

Key Features

Supported Movement Types

The Player System supports an extensive range of movement mechanics:


Architecture & Core Concepts

The Player System follows a component-entity-system (CES) architecture that leverages Bevy’s built-in systems and custom plugins. The architecture is designed around several key principles:

Component-Based Design

Each player behavior is implemented as a separate component that can be attached to player entities. This allows for:

Event-Driven Communication

The Player System uses Bevy’s event system for inter-component communication:

Resource-Based Queues

For high-frequency operations and batch processing, the Player System uses resource queues:

Priority-Based State Management

The state management system implements a sophisticated priority system:


System Components

Player Modes System

The Player Modes System manages high-level player modes and control states. This system is fundamental to organizing different player behaviors and capabilities.

Core Concepts

Player Modes represent different capability sets or gameplay modes that the player can be in:

Control States represent different input handling modes:

Component Structure

PlayerMode Component
pub struct PlayerMode {
    pub name: String,              // Unique identifier for the mode
    pub mode_enabled: bool,         // Whether this mode is currently enabled
    pub is_current_state: bool,    // Whether this mode is the active mode
}

Field Descriptions:

PlayerControlState Component
pub struct PlayerControlState {
    pub name: String,                                        // State identifier
    pub mode_enabled: bool,                                  // Whether the state is enabled
    pub is_current_state: bool,                              // Whether this is the active state
    pub avoid_to_set_regular_mode_when_active: bool,        // Prevents automatic regular mode switching
}

Field Descriptions:

PlayerModesSystem Component
pub struct PlayerModesSystem {
    pub use_default_players_mode: bool,         // Whether to use default mode
    pub default_players_mode_name: String,      // Name of the default player mode
    pub current_players_mode_name: String,      // Currently active player mode
    pub player_modes: Vec,          // List of available player modes
    
    pub default_control_state_name: String,      // Default control state
    pub current_control_state_name: String,     // Currently active control state
    pub player_control_states: Vec, // List of available control states
    
    pub change_mode_enabled: bool,              // Whether mode changes are enabled
    pub change_player_control_enabled: bool,   // Whether control state changes are enabled
}

Field Descriptions:

Event System

SetPlayerModeEvent

Fires when a player mode should be changed:

pub struct SetPlayerModeEvent {
    pub player_entity: Entity,  // Entity of the player to change mode for
    pub mode_name: String,      // Name of the mode to switch to
}
SetControlStateEvent

Fires when a control state should be changed:

pub struct SetControlStateEvent {
    pub player_entity: Entity,   // Entity of the player to change state for
    pub state_name: String,     // Name of the control state to switch to
}
PlayerModeChangedEvent

Fired when a mode or control state has been successfully changed:

pub struct PlayerModeChangedEvent {
    pub player_entity: Entity,   // Player entity
    pub new_mode_name: String,  // Name of the new mode/state
    pub is_control_state: bool, // True if this was a control state change, false if player mode
}

Mode Management Logic

Mode Change Processing

The system processes mode changes through the following logic:

  1. Validation: Checks if the requested mode exists and is enabled
  2. Deactivation: Deactivates any currently active modes of the same type
  3. Activation: Activates the requested mode
  4. Event Firing: Fires appropriate events to notify other systems
Control State Management

Control states follow similar logic to player modes but include additional considerations:

  1. Exclusivity: Only one control state can be active at a time
  2. Avoid Regular Mode Logic: Respects the avoid_to_set_regular_mode_when_active flag
  3. Priority Handling: Some control states can prevent regular mode activation

Integration Points

The Player Modes System integrates with:


Player State System

The Player State System provides sophisticated state management with priority handling, duration management, and interrupt capabilities. This system is essential for managing temporary player conditions like being stunned, under effects, or in specific action states.

Core Concepts

Player States represent temporary conditions or modes that the player can be in:

State Priority System

The priority system allows for sophisticated state management:

Component Structure

PlayerStateInfo Component
pub struct PlayerStateInfo {
    pub name: String,              // Unique identifier for the state
    pub state_enabled: bool,        // Whether this state is enabled
    pub state_active: bool,        // Whether this state is currently active
    pub state_priority: i32,       // Priority level of the state
    pub can_be_interrupted: bool,  // Whether this state can be interrupted
    pub use_state_duration: bool,  // Whether this state has a time limit
    pub state_duration: f32,       // Duration of the state in seconds
    pub current_duration_timer: f32, // Current timer value
}

Field Descriptions:

PlayerStateSystem Component
pub struct PlayerStateSystem {
    pub player_states_enabled: bool,  // Whether the state system is enabled
    pub player_state_list: Vec, // List of all available states
    pub current_state_name: String,   // Name of the currently active state
}

Field Descriptions:

Event System

SetPlayerStateEvent

Used to request a state change:

pub struct SetPlayerStateEvent {
    pub player_entity: Entity,  // Entity of the player
    pub state_name: String,      // Name of the state to activate
}
PlayerStateChangedEvent

Fired when a state has been activated or deactivated:

pub struct PlayerStateChangedEvent {
    pub player_entity: Entity,  // Player entity
    pub state_name: String,    // Name of the changed state
    pub active: bool,           // True if state was activated, false if deactivated
}

State Management Logic

State Activation Process
  1. State Lookup: Finds the requested state in the player state list
  2. Enabled Check: Verifies the state is enabled
  3. Priority Validation: Checks if the state can interrupt current active states
  4. Deactivation: Deactivates conflicting states
  5. Activation: Activates the new state
  6. Event Firing: Notifies other systems of the state change
Priority Handling

The priority system follows these rules:

  1. Active State Check: Identifies currently active states
  2. Interrupt Permission: Checks if active states can be interrupted
  3. Priority Comparison: Compares priorities to determine if interruption is allowed
  4. Decision Making: Allows or denies the state change based on priority rules
Duration Management

For time-limited states:

  1. Timer Initialization: Sets the timer to zero when state activates
  2. Time Accumulation: Accumulates time using Bevy’s delta time
  3. Expiration Check: Checks if the timer exceeds the state duration
  4. Automatic Deactivation: Deactivates the state when duration expires
  5. Event Firing: Notifies systems of the automatic expiration

State Types and Examples

High Priority States (Priority 100+)
Medium Priority States (Priority 50-99)
Low Priority States (Priority 1-49)

Integration with Other Systems

Animation System Integration
Input System Integration
Physics System Integration

Player Idle System

The Player Idle System manages idle behaviors and animations when the player is not actively using input. This system enhances the player experience by providing realistic idle animations and behaviors that make the character feel more alive and responsive.

Core Concepts

Idle States represent different idle behaviors that can be cycled through:

Idle Trigger Conditions

The system monitors various conditions to determine when to activate idle states:

Component Structure

IdleInfo Component
pub struct IdleInfo {
    pub name: String,   // Identifier for the idle state
    pub duration: f32,  // How long this idle animation/state lasts
}

Field Descriptions:

PlayerIdleSystem Component
pub struct PlayerIdleSystem {
    pub idle_enabled: bool,                    // Whether idle system is enabled
    pub idle_active: bool,                      // Whether idle system is currently active
    pub current_idle_index: usize,              // Index of currently playing idle state
    pub play_random_idle: bool,                 // Whether to play random idle states
    pub idle_info_list: Vec,          // List of available idle states
    pub timer: f32,                             // Timer for idle state progression
    pub idle_stopped_automatically: bool,       // Whether idle was stopped by input
}

Field Descriptions:

Idle State Management

Idle Activation Logic

The system follows this process for idle activation:

  1. Input Monitoring: Continuously monitors player input state
  2. Inactivity Detection: Detects when player has been inactive for threshold duration
  3. Activation Decision: Determines whether to activate idle based on conditions
  4. State Selection: Chooses appropriate idle state from available options
  5. Timer Initialization: Starts timer for the selected idle state
Idle State Progression
  1. Timer Accumulation: Accumulates time while idle state is active
  2. Duration Check: Compares elapsed time with state duration
  3. Next State Selection: Chooses next idle state based on configuration
  4. Random vs Sequential: Uses random selection or sequential progression
  5. State Transition: Transitions to new idle state
  6. Repeat Process: Continues cycling through idle states
Idle Deactivation

Idle states are deactivated when:

Idle State Types

Sequential Idle States

Played in order for predictable behavior:

  1. Idle 1: Basic standing pose (5.0 seconds)
  2. Idle 2: Looking around (5.0 seconds)
  3. Idle 3: Equipment check (5.0 seconds)
  4. Loop back to Idle 1: Continuous cycle
Random Idle States

Selected randomly for varied behavior:

Integration Points

Input System Integration
Animation System Integration
Environmental Integration

The NavMesh Override System allows external systems to temporarily take control of player movement for purposes like cutscenes, scripted sequences, or AI-directed movement. This system provides a bridge between the player’s autonomous control and externally-driven movement.

Core Concepts

NavMesh Override represents a temporary state where player movement is controlled by external navigation systems rather than direct player input:

Override States

The system supports different override states:

Component Structure

pub struct NavMeshOverride {
    pub active: bool,                              // Whether override is currently active
    pub target_entity: Option,             // Optional target entity to follow
    pub target_position: Option,           // Optional target position to move to
    pub path_status: String,                       // Current status of the pathfinding
}

Field Descriptions:

Event System

EnableNavMeshOverrideEvent
pub struct EnableNavMeshOverrideEvent {
    pub entity: Entity,  // Player entity to enable override for
}
DisableNavMeshOverrideEvent
pub struct DisableNavMeshOverrideEvent {
    pub entity: Entity,  // Player entity to disable override for
}
SetNavMeshTargetEvent
pub struct SetNavMeshTargetEvent {
    pub entity: Entity,                 // Player entity to set target for
    pub target_position: Option, // Target world position
    pub target_entity: Option, // Target entity to follow
}

Override Logic

Enable Process
  1. Entity Validation: Validates that the entity exists and has NavMesh override component
  2. State Activation: Sets the active flag to true
  3. Status Update: Updates path status to indicate override is active
  4. Event Logging: Logs the enable operation for debugging
Disable Process
  1. State Deactivation: Sets active flag to false
  2. Target Cleanup: Clears target entity and position references
  3. Status Reset: Resets path status to “Idle”
  4. Control Return: Returns control to normal player input systems
Target Setting Process
  1. Active Check: Verifies that override is currently active
  2. Target Assignment: Sets either target position or target entity
  3. Status Update: Updates path status to “Moving”
  4. Path Request: Initiates pathfinding request (in full implementation)

Movement Logic

Target Resolution

The system resolves targets through this process:

  1. Position Priority: Uses target position if available
  2. Entity Fallback: Uses entity position if target position is not set
  3. Validation: Validates that resolved target is valid
  4. Distance Calculation: Calculates distance to target
Movement Simulation
  1. Distance Check: Calculates distance between player and target
  2. Proximity Detection: Determines if player is close enough to consider target reached
  3. Movement Application: Applies movement towards target (simplified in current implementation)
  4. Status Updates: Updates path status based on movement progress

Ragdoll System

The Ragdoll System manages physics-based player deaths and falls, providing realistic ragdoll physics for player characters. This system enables characters to fall realistically, respond to impacts, and recover from ragdoll states through animation blending.

Core Concepts

Ragdoll Physics provides a realistic simulation of player character bodies when they fall, die, or are knocked down:

Ragdoll States

The system implements a state machine with three main states:

Animated State
Ragdolled State
BlendToAnim State

Component Structure

Ragdoll Component
pub struct Ragdoll {
    pub current_state: RagdollState,       // Current ragdoll state
    pub active: bool,                     // Whether ragdoll system is active
    pub time_to_get_up: f32,              // Time required to get up from ragdoll
    pub max_ragdoll_velocity: f32,        // Maximum velocity before forced ragdoll
    pub timer: f32,                       // Internal timer for state management
    pub on_ground: bool,                   // Whether ragdoll body is on ground
    pub root_bone: Option,        // Optional reference to root bone
    pub body_parts: Vec,          // Vector of all body part entities
}

Field Descriptions:

RagdollState Enum
pub enum RagdollState {
    Animated,      // Normal animation state
    Ragdolled,     // Physics-controlled ragdoll state
    BlendToAnim,   // Transition state back to animation
}

Event System

ActivateRagdollEvent
pub struct ActivateRagdollEvent {
    pub entity: Entity,                    // Entity to activate ragdoll for
    pub force_direction: Option,    // Optional direction for force application
    pub force_magnitude: f32,             // Magnitude of force to apply
}
DeactivateRagdollEvent
pub struct DeactivateRagdollEvent {
    pub entity: Entity,  // Entity to deactivate ragdoll for
}

State Machine Logic

State Transitions
Animated to Ragdolled
  1. Trigger Detection: Detects trigger condition for ragdoll activation
  2. Force Application: Applies specified force if provided
  3. State Change: Transitions to Ragdolled state
  4. Timer Reset: Resets timer for state management
  5. Physics Activation: Activates physics simulation for body parts
Ragdolled to BlendToAnim
  1. Timer Monitoring: Monitors timer for duration requirements
  2. Ground Check: Verifies ragdoll body is on ground
  3. Velocity Check: Ensures ragdoll velocity is below threshold
  4. Transition Decision: Makes decision to begin recovery
  5. State Change: Transitions to BlendToAnim state
BlendToAnim to Animated
  1. Timer Accumulation: Accumulates time during blend state
  2. Blend Calculation: Calculates appropriate blend ratio
  3. Animation Control: Gradually returns control to animation system
  4. State Completion: Transitions to Animated state when blend complete

Physics Integration

Body Part Management

The system manages ragdoll physics through:

Force Application

Force application includes:

Ground Detection

Ground detection system:


Sprite Animator System

The Sprite Animator System manages sprite sheet animation states and logic for 2.5D and 2D player characters. This system provides automatic animation state transitions based on player movement, input, and character status.

Core Concepts

Sprite Animation provides frame-based animation for 2D and 2.5D characters:

Animation States

The system supports multiple animation states:

Movement States

Component Structure

SpriteAnimator Component
pub struct SpriteAnimator {
    pub active: bool,                 // Whether animation system is active
    pub current_state: SpriteAnimationState, // Current animation state
    pub flip_x: bool,                 // Whether sprite should be flipped horizontally
    pub is_grounded: bool,           // Whether character is currently grounded
    pub velocity: Vec3,               // Current character velocity
}

Field Descriptions:

SpriteAnimationState Enum
pub enum SpriteAnimationState {
    Idle,   // Stationary character
    Walk,   // Walking animation
    Run,    // Running animation
    Jump,   // Jumping animation
    Fall,   // Falling animation
    Land,   // Landing animation
}

Animation State Logic

State Determination

The system determines the appropriate animation state through this logic:

  1. Grounded Check: Determines if character is grounded or in air
  2. Vertical Velocity Analysis: Analyzes vertical velocity for jump/fall states
  3. Horizontal Speed Calculation: Calculates horizontal movement speed
  4. Speed Threshold Comparison: Compares speed against thresholds for walk/run
  5. State Assignment: Assigns appropriate animation state
State Priority System

Animation states follow this priority order:

  1. Jump/Fall: Highest priority for aerial states
  2. Land: High priority for landing transitions
  3. Run: Higher priority for fast movement
  4. Walk: Medium priority for normal movement
  5. Idle: Lowest priority for stationary state
Speed Thresholds

The system uses speed thresholds for state transitions:

Direction Handling

Flip Logic

Sprite flipping is handled through this logic:

  1. Movement Analysis: Analyzes horizontal movement direction
  2. Direction Determination: Determines if character is moving left or right
  3. Flip Decision: Decides whether to flip sprite based on direction
  4. Component Update: Updates both animator and sprite component flip flags

Upper Body Rotation System

The Upper Body Rotation System handles procedural rotation of the player’s upper body (spine, chest) to face targets. This system provides realistic character aiming and looking behavior that enhances player immersion and gameplay mechanics.

Core Concepts

Upper Body Rotation allows characters to:

Rotation Components

The system targets specific body parts:

Spine Rotation
Chest Rotation

Component Structure

UpperBodyRotation Component
pub struct UpperBodyRotation {
    pub enabled: bool,                        // Whether system is enabled
    pub rotation_speed: f32,                  // Speed of rotation interpolation
    pub max_bending_angle: f32,               // Maximum rotation angle
    pub horizontal_enabled: bool,             // Enable horizontal rotation
    pub vertical_enabled: bool,              // Enable vertical rotation
    pub spine_bone: Option,           // Reference to spine bone entity
    pub chest_bone: Option,           // Reference to chest bone entity
}

Field Descriptions:

UpperBodyTarget Component
pub struct UpperBodyTarget {
    pub target_entity: Option,        // Entity to look at
    pub target_position: Option,       // World position to look at
}

Field Descriptions:

Rotation Logic

Target Resolution

The system resolves targets through this priority:

  1. Entity Target: Uses target entity if provided and valid
  2. Position Target: Uses target position if entity target is not available
  3. Default Behavior: Returns to neutral position if no target is available
Rotation Calculation
  1. Direction Vector: Calculates direction from character to target
  2. Local Transformation: Converts world direction to local character space
  3. Angle Limitation: Limits rotation angle to maximum bending angle
  4. Constraint Application: Applies horizontal/vertical constraints
  5. Rotation Interpolation: Interpolates from current to target rotation
Smooth Transitions

The system implements smooth transitions through:

  1. Current Rotation: Captures current bone rotation
  2. Target Rotation: Calculates desired rotation towards target
  3. Interpolation: Uses spherical linear interpolation (slerp) for smooth transitions
  4. Speed Control: Controls transition speed through rotation_speed parameter

Extra Movement Systems

The Extra Movement Systems provide advanced movement capabilities beyond basic walking and running. These systems handle specialized movement types like flying, swimming, wall-running, and other unique movement mechanics that can be enabled based on game requirements.

Movement System Overview

Each extra movement system is implemented as a separate plugin that can be enabled independently:

Common Architecture

All extra movement systems follow a common architectural pattern:

Plugin Structure

Each system is implemented as a Bevy plugin that:

Component Design

Common component patterns include:

Fly System

Core Functionality

The Fly System enables three-dimensional free-form movement:

Jetpack System

Core Functionality

The Jetpack System provides controlled flight with resource management:

Wall Run System

Core Functionality

The Wall Run System enables movement along vertical surfaces:

Swim System

Core Functionality

The Swim System handles underwater and surface swimming:

System Integration

Input Integration

Each system integrates with the input system through:

Physics Integration

All systems integrate with physics through:

Animation Integration

Integration with animation systems includes:


Advanced Features

Priority-Based State Management

The Player System implements a sophisticated priority-based state management system that allows for complex interactions between different player states and behaviors.

Priority Hierarchy

States are organized in a hierarchical priority system:

Critical States (Priority 100+)
High Priority States (Priority 50-99)
Medium Priority States (Priority 10-49)
Low Priority States (Priority 1-9)

State Interaction Rules

Interrupt Handling
Concurrent State Management

Event-Driven Architecture

The Player System uses an event-driven architecture that promotes loose coupling and flexible system interactions.

Event Types

State Change Events

Events fired when player states change:

Action Events

Events triggered by player actions:

System Events

Events for system-level communications:

Event Processing

Event Queues

Events are processed through efficient queue systems:

Event Handling

Event handling follows established patterns:

System Communication

Loose Coupling

Systems communicate through events rather than direct references:

Event Documentation

All events are well-documented:

Animation Integration

The Player System provides comprehensive integration with animation systems to ensure smooth and realistic character behavior.

Animation State Mapping

Movement Animation Mapping

Each movement state is mapped to appropriate animations:

State Transition Animation

Smooth transitions between animation states:

Animation Customization

Animation Selection

Flexible animation selection based on context:

Animation Modification

Dynamic modification of animations:

Performance Optimization

Animation Caching

Efficient animation management:

Update Optimization

Optimized animation updates:


System Integration

Character Controller Integration

The Player System integrates seamlessly with the Character Controller system to provide comprehensive character movement and behavior.

Movement Coordination

State Coordination

The Player System coordinates with the Character Controller through:

Control Flow

The control flow between systems follows this pattern:

  1. Player System: Determines desired player state and behavior
  2. Character Controller: Processes movement based on player state
  3. Physics System: Applies physics-based movement and collision
  4. Animation System: Updates animations based on movement
  5. Feedback Systems: Provide feedback to player about movement state

Integration Points

Component Integration

Components from both systems work together:

System Communication

Systems communicate through well-defined interfaces:

Camera System Integration

The Player System integrates with the Camera System to provide camera behavior that follows player state and movement.

Camera State Coordination

Movement-Based Camera

Camera behavior changes based on player movement:

Camera Modes

Different camera modes based on player state:

Camera Control Integration

Input Integration

Camera input integrates with player input:

State-Based Camera

Camera behavior based on player state:

Input System Integration

The Player System integrates with the Input System to provide comprehensive and responsive input handling.

Input Event Processing

Event Handling

Input events are processed through the Player System:

Input State Management

Input state is managed comprehensively:

Input Customization

Rebinding Support

Comprehensive input rebinding support:

Sensitivity Settings

Fine-grained sensitivity settings:

Animation System Integration

The Player System integrates with animation systems to provide smooth and realistic character animation.

Animation Coordination

State-Based Animation

Animation state coordinates with player state:

Movement-Based Animation

Animation based on player movement:

Animation Customization

Animation Selection

Flexible animation selection:

Animation Modification

Dynamic animation modification:

Physics System Integration

The Player System integrates with physics systems to provide realistic physical interaction.

Physics Coordination

Movement Physics

Physics-based player movement:

Collision Physics

Physics-based collision handling:

Physics Customization

Physics Properties

Customizable physics properties:

Physics Behavior

Customizable physics behavior:

UI System Integration

The Player System integrates with UI systems to provide visual feedback about player state and behavior.

State Visualization

State Indicators

Visual indicators of player state:

Status Display

Comprehensive status display:

Interaction Feedback

Action Feedback

Feedback for player actions:

Environmental Feedback

Feedback from the environment:


Usage Patterns

Basic Player Setup

The most common usage pattern involves setting up a basic player character with standard movement capabilities.

Player Entity Creation

// Basic player entity setup
let player_entity = commands.spawn((
    Player,
    PlayerModesSystem::default(),
    PlayerStateSystem::default(),
    PlayerIdleSystem::default(),
    // Add other player components as needed
)).id();

Component Configuration

// Configure player modes
let mut player_modes = PlayerModesSystem::default();
player_modes.player_modes = vec![
    PlayerMode {
        name: "Weapons".to_string(),
        mode_enabled: true,
        is_current_state: true,
    },
    PlayerMode {
        name: "Powers".to_string(),
        mode_enabled: true,
        is_current_state: false,
    },
];
// Configure player states
let mut player_states = PlayerStateSystem::default();
player_states.player_state_list = vec![
    PlayerStateInfo {
        name: "Walking".to_string(),
        state_enabled: true,
        state_active: true,
        state_priority: 10,
        can_be_interrupted: true,
        use_state_duration: false,
        state_duration: 0.0,
        current_duration_timer: 0.0,
    },
    // Add more states as needed
];

Integration Setup

// Setup input system integration
app.add_plugins(InputPlugin)
   .add_plugins(PlayerPlugin);
// Setup animation system integration
app.add_systems(Update, (
    update_player_animation,
    handle_player_state_changes,
));

Advanced Movement Setup

For games requiring advanced movement capabilities, the Player System can be configured with multiple movement systems.

Extra Movement Configuration

// Enable multiple movement systems
app.add_plugins((
    ExtraMovementsPlugin,
    fly::FlyPlugin,
    swim::SwimPlugin,
    wall_run::WallRunPlugin,
    jetpack::JetpackPlugin,
));
// Configure player for multiple movement types
let mut player_states = PlayerStateSystem::default();
player_states.player_state_list = vec![
    PlayerStateInfo {
        name: "Flying".to_string(),
        state_enabled: true,
        state_active: false,
        state_priority: 30,
        can_be_interrupted: true,
        use_state_duration: false,
        state_duration: 0.0,
        current_duration_timer: 0.0,
    },
    PlayerStateInfo {
        name: "Swimming".to_string(),
        state_enabled: true,
        state_active: false,
        state_priority: 25,
        can_be_interrupted: true,
        use_state_duration: false,
        state_duration: 0.0,
        current_duration_timer: 0.0,
    },
    // Add more movement states
];

Movement State Management

// System to handle movement state changes
pub fn handle_movement_state_changes(
    mut set_state_queue: ResMut,
    keys: Res<ButtonInput>,
    query: Query,
) {
    let player_entity = /* get player entity */;
    
    // Handle fly mode activation
    if keys.just_pressed(KeyCode::KeyF) {
        set_state_queue.0.push(SetPlayerStateEvent {
            player_entity,
            state_name: "Flying".to_string(),
        });
    }
    
    // Handle swim mode activation
    if keys.just_pressed(KeyCode::KeyS) {
        set_state_queue.0.push(SetPlayerStateEvent {
            player_entity,
            state_name: "Swimming".to_string(),
        });
    }
}

Combat Integration Pattern

Games with combat systems can integrate the Player System with combat mechanics for enhanced gameplay.

Combat State Integration

// Integrate with combat system
pub fn handle_combat_states(
    mut set_mode_queue: ResMut,
    combat_events: Res,
    query: Query,
) {
    let player_entity = /* get player entity */;
    
    // Switch to combat mode when combat starts
    if combat_events.combat_started {
        set_mode_queue.0.push(SetPlayerModeEvent {
            player_entity,
            mode_name: "Combat".to_string(),
        });
    }
    
    // Switch back to exploration mode when combat ends
    if combat_events.combat_ended {
        set_mode_queue.0.push(SetPlayerModeEvent {
            player_entity,
            mode_name: "Exploration".to_string(),
        });
    }
}

Combat Animation Integration

// Integrate with combat animations
pub fn handle_combat_animations(
    mut sprite_query: Query,
    combat_events: Res,
) {
    for mut animator in sprite_query.iter_mut() {
        // Trigger combat animations
        if combat_events.attack_initiated {
            animator.current_state = SpriteAnimationState::Attack;
        }
        
        // Return to movement animations
        if combat_events.attack_completed {
            animator.current_state = SpriteAnimationState::Idle;
        }
    }
}

Vehicle Integration Pattern

For games with vehicles, the Player System can integrate with vehicle systems for seamless transitions.

Vehicle State Management

// Handle vehicle entry/exit
pub fn handle_vehicle_states(
    mut set_control_queue: ResMut,
    vehicle_events: Res,
    query: Query,
) {
    let player_entity = /* get player entity */;
    
    // Enter vehicle
    if vehicle_events.vehicle_entered {
        set_control_queue.0.push(SetControlStateEvent {
            player_entity,
            state_name: "Driving".to_string(),
        });
    }
    
    // Exit vehicle
    if vehicle_events.vehicle_exited {
        set_control_queue.0.push(SetControlStateEvent {
            player_entity,
            state_name: "Regular".to_string(),
        });
    }
}

Vehicle Animation Integration

// Integrate with vehicle animations
pub fn handle_vehicle_animations(
    mut animator_query: Query,
    vehicle_state: Res,
) {
    for mut animator in animator_query.iter_mut() {
        // Use vehicle-specific animations
        if vehicle_state.in_vehicle {
            animator.current_state = SpriteAnimationState::Driving;
        } else {
            // Return to character animations
            animator.current_state = SpriteAnimationState::Idle;
        }
    }
}

AI Integration Pattern

For games with AI systems, the Player System can be controlled by AI for scripted sequences.

// Setup AI-controlled player movement
pub fn setup_ai_control(
    mut commands: Commands,
    mut nav_override_queue: ResMut,
    ai_targets: Res,
) {
    let player_entity = /* get player entity */;
    
    // Add NavMesh override component if not present
    if !nav_override_query.get(player_entity).is_ok() {
        commands.entity(player_entity).insert(NavMeshOverride::default());
    }
    
    // Set AI target
    nav_override_queue.0.push(SetNavMeshTargetEvent {
        entity: player_entity,
        target_position: Some(ai_targets.next_target),
        target_entity: None,
    });
}

AI Sequence Management

// Manage AI sequences
pub fn manage_ai_sequences(
    mut enable_override_queue: ResMut,
    mut disable_override_queue: ResMut,
    ai_state: Res,
    query: Query,
) {
    let player_entity = /* get player entity */;
    
    // Enable AI control
    if ai_state.sequence_started && !query.get(player_entity).unwrap().active {
        enable_override_queue.0.push(EnableNavMeshOverrideEvent {
            entity: player_entity,
        });
    }
    
    // Disable AI control
    if ai_state.sequence_completed && query.get(player_entity).unwrap().active {
        disable_override_queue.0.push(DisableNavMeshOverrideEvent {
            entity: player_entity,
        });
    }
}

Save System Integration

The Player System can integrate with save systems to persist player state.

State Serialization

// Serialize player state for saving
pub fn serialize_player_state(
    query: Query,
) -> PlayerStateData {
    let (modes, states, idle) = query.single();
    
    PlayerStateData {
        current_mode: modes.current_players_mode_name.clone(),
        current_state: states.current_state_name.clone(),
        current_idle: idle.current_idle_index,
        // Serialize other state data
    }
}
// Deserialize player state from save
pub fn deserialize_player_state(
    state_data: PlayerStateData,
    mut set_mode_queue: ResMut,
    mut set_state_queue: ResMut,
) {
    let player_entity = /* get player entity */;
    
    // Restore player mode
    set_mode_queue.0.push(SetPlayerModeEvent {
        player_entity,
        mode_name: state_data.current_mode,
    });
    
    // Restore player state
    set_state_queue.0.push(SetPlayerStateEvent {
        player_entity,
        state_name: state_data.current_state,
    });
}

Multiplayer Integration Pattern

For multiplayer games, the Player System needs to be adapted for network synchronization.

Network State Synchronization

// Synchronize player state over network
pub fn sync_player_state(
    mut query: Query,
    network_events: Res,
) {
    // Apply remote state changes
    for event in network_events.state_changes.iter() {
        if let Ok(mut states) = query.get_mut(event.player_entity) {
            states.current_state_name = event.new_state.clone();
        }
    }
}

Network Event Handling

// Handle network events
pub fn handle_network_events(
    mut set_mode_queue: ResMut,
    mut set_state_queue: ResMut,
    network_events: Res,
) {
    for event in network_events.mode_changes.iter() {
        set_mode_queue.0.push(SetPlayerModeEvent {
            player_entity: event.player_entity,
            mode_name: event.mode_name.clone(),
        });
    }
    
    for event in network_events.state_changes.iter() {
        set_state_queue.0.push(SetPlayerStateEvent {
            player_entity: event.player_entity,
            state_name: event.state_name.clone(),
        });
    }
}