bevy-ichun 0.6.0

A simple kinematic character controller for avian3d
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
//! # Input Handling for Character Controller
//!
//! This module provides systems and components for translating player input into
//! character movement events. It supports keyboard and mouse input.
//!
//! The input systems detect player input and generate events that the movement
//! systems respond to. This separation allows for flexible input configuration
//! without modifying the movement logic.
//!
//! ## Features
//!
//! * Customizable key bindings for all actions
//! * Support for multiple keys per action
//! * Toggleable running and floating modes
//! * Optional activation keys for rotation (e.g. right mouse button)
//! * Global and per-character input handling activation
//!
//! ## Components
//!
//! * [`KccInputConfig`]: Configures input bindings and behavior
//!
//! ## Systems
//!
//! * `movement_input_sys`: Handles horizontal movement key input for movement
//! * `run_input_sys`: Handles run key input (toggle or hold)
//! * `jump_input_sys`: Handles jump key input
//! * `float_input_sys`: Handles float / glide key input (toggle or hold)
//! * `rotation_input_sys`: Handles mouse input for camera rotation
use avian3d::math::{Scalar, Vector2};
use bevy::{
    app::{Plugin, Update},
    ecs::{
        component::Component,
        entity::Entity,
        message::MessageWriter,
        query::With,
        resource::Resource,
        schedule::IntoScheduleConfigs,
        system::{Query, Res},
    },
    input::{ButtonInput, keyboard::KeyCode, mouse::AccumulatedMouseMotion},
    platform::collections::HashSet,
};

use crate::{
    kcc::Kcc,
    movement_events::{
        IchunFloatEvent, IchunJumpEvent, IchunMoveEvent, IchunRotateEvent, IchunRunEvent,
        KccMovementEventsConfig,
    },
    system_sets::IchunSystemSet,
};

/// Component to configure the input to move the KCC
///
/// This component defines the key bindings and input behavior for controlling
/// a character. It must be attached to an entity that also has the [`Kcc`] and
/// [`KccMovementConfig`] components.
///
/// It allows customizing keys for movement, running, jumping, floating, and
/// camera rotation, as well as setting toggle/hold behavior for actions.
///
/// # Example
///
/// ```rust
/// use bevy_ichun::input::{KccInputConfig, RunConditions};
/// use bevy::input::keyboard::KeyCode;
///
/// // Create a custom input configuration with WASD movement,
/// // Space to jump, and Left Shift to run
/// let input_config = KccInputConfig::new(
///     // Forward keys
///     [KeyCode::KeyW],
///     // Backward keys
///     [KeyCode::KeyS],
///     // Left keys
///     [KeyCode::KeyA],
///     // Right keys
///     [KeyCode::KeyD],
///     // Run conditions
///     RunConditions { forward_only: true },
///     // Run is toggled
///     true,
///     // Run keys
///     [KeyCode::ShiftLeft],
///     // Jump keys
///     [KeyCode::Space],
///     // Float is held
///     false,
///     // Float keys
///     [KeyCode::Space],
///     // Rotation activation (none = always active)
///     None::<[KeyCode; 0]>,
///     // Input handling active
///     true,
/// );
/// ```
#[derive(Component)]
#[require(Kcc, KccMovementEventsConfig)]
pub struct KccInputConfig {
    /// Keys that trigger forward movement
    pub forward: HashSet<KeyCode>,
    /// Keys that trigger backward movement
    pub backward: HashSet<KeyCode>,
    /// Keys that trigger leftward movement
    pub left: HashSet<KeyCode>,
    /// Keys that trigger rightward movement
    pub right: HashSet<KeyCode>,
    /// Conditions that must be met for running to be allowed
    pub run_conditions: RunConditions,
    /// Determines the running mode:
    /// - If `true`: Running is toggled on/off with a key press
    /// - If `false`: Running is active only while the run key is held down
    pub is_running_toggled: bool,
    /// Keys that trigger running
    pub run: HashSet<KeyCode>,
    /// Keys that trigger jumping
    pub jump: HashSet<KeyCode>,
    /// Determines the floating mode:
    /// - If `true`: Floating is toggled on/off with a key press
    /// - If `false`: Floating is active only while the float key is held down
    pub is_floating_toggled: bool,
    /// Keys that trigger floating/gliding
    pub float: HashSet<KeyCode>,
    /// Button which needs to be pressed to activate rotation input (e.g., right click in MMORPGs)
    /// None if no button needs to be pressed to activate rotation
    pub rotation_activation: Option<HashSet<KeyCode>>,
    /// Field which decides if input for this KCC is handled or not
    pub input_handling_active: bool,
}

/// The default input is:
/// Movement with W, A, S, D,
/// Running can be toggled with left Shift
/// Jumping with Space
/// Floating with holding down Space
impl Default for KccInputConfig {
    fn default() -> Self {
        let mut forward = HashSet::new();
        forward.insert(KeyCode::KeyW);

        let mut backward = HashSet::new();
        backward.insert(KeyCode::KeyS);

        let mut left = HashSet::new();
        left.insert(KeyCode::KeyA);

        let mut right = HashSet::new();
        right.insert(KeyCode::KeyD);

        let mut run = HashSet::new();
        run.insert(KeyCode::ShiftLeft);

        let mut jump = HashSet::new();
        jump.insert(KeyCode::Space);

        let mut float = HashSet::new();
        float.insert(KeyCode::Space);

        Self {
            forward,
            backward,
            left,
            right,
            run_conditions: RunConditions { forward_only: true },
            is_running_toggled: true,
            run,
            jump,
            is_floating_toggled: false,
            float,
            rotation_activation: None,
            input_handling_active: true,
        }
    }
}

impl KccInputConfig {
    pub fn new(
        forward: impl IntoIterator<Item = KeyCode>,
        backward: impl IntoIterator<Item = KeyCode>,
        left: impl IntoIterator<Item = KeyCode>,
        right: impl IntoIterator<Item = KeyCode>,
        run_conditions: RunConditions,
        is_running_toggled: bool,
        run: impl IntoIterator<Item = KeyCode>,
        jump: impl IntoIterator<Item = KeyCode>,
        is_floating_toggled: bool,
        float: impl IntoIterator<Item = KeyCode>,
        rotation_activation: Option<impl IntoIterator<Item = KeyCode>>,
        input_handling_active: bool,
    ) -> Self {
        Self {
            forward: forward.into_iter().collect(),
            backward: backward.into_iter().collect(),
            left: left.into_iter().collect(),
            right: right.into_iter().collect(),
            run_conditions,
            is_running_toggled,
            run: run.into_iter().collect(),
            jump: jump.into_iter().collect(),
            is_floating_toggled,
            float: float.into_iter().collect(),
            rotation_activation: rotation_activation.map(|keys| keys.into_iter().collect()),
            input_handling_active,
        }
    }
}

/// Conditions to check if running is possible
///
/// This struct defines conditions that must be met for a character
/// to be allowed to enter the running state.
///
/// # Fields
///
/// * `forward_only`: If true, running is only allowed when moving forward
#[derive(Default)]
pub struct RunConditions {
    /// If true, running is only allowed when moving forward
    pub forward_only: bool,
}

/// Resource which can (de)activate input handling for all KCC
#[derive(Resource)]
struct InputHandling {
    input_handling_active: bool,
}

pub struct IchunInputPlugin;

impl Plugin for IchunInputPlugin {
    fn build(&self, app: &mut bevy::app::App) {
        app.insert_resource(InputHandling {
            input_handling_active: true, // Default to active
        })
        .add_systems(
            Update,
            (
                rotation_input_sys,
                jump_input_sys,
                run_input_sys,
                movement_input_sys,
                float_input_sys,
            )
                .chain()
                .in_set(IchunSystemSet::InputSet),
        );
    }
}

fn movement_input_sys(
    mut movement_event_writer: MessageWriter<IchunMoveEvent>,
    keyboard_input_res: Res<ButtonInput<KeyCode>>,
    input_handling_res: Res<InputHandling>,
    kcc_qry: Query<(Entity, &KccInputConfig), With<Kcc>>,
) {
    if !input_handling_res.input_handling_active {
        return;
    }

    for (entity, input) in kcc_qry.iter() {
        if !input.input_handling_active {
            continue;
        }

        let right_pressed = input
            .right
            .iter()
            .any(|&key| keyboard_input_res.pressed(key));
        let left_pressed = input
            .left
            .iter()
            .any(|&key| keyboard_input_res.pressed(key));
        let forward_pressed = input
            .forward
            .iter()
            .any(|&key| keyboard_input_res.pressed(key));
        let backward_pressed = input
            .backward
            .iter()
            .any(|&key| keyboard_input_res.pressed(key));

        let horizontal = right_pressed as i8 - left_pressed as i8;
        let vertical = forward_pressed as i8 - backward_pressed as i8;

        let direction =
            Vector2::new(horizontal as Scalar, -vertical as Scalar).clamp_length_max(1.0);

        if direction != Vector2::ZERO {
            movement_event_writer.write(IchunMoveEvent { entity, direction });
        }
    }
}

fn run_input_sys(
    mut run_event_writer: MessageWriter<IchunRunEvent>,
    keyboard_input_res: Res<ButtonInput<KeyCode>>,
    input_handling_res: Res<InputHandling>,
    kcc_qry: Query<(Entity, &KccInputConfig, &KccMovementEventsConfig), With<Kcc>>,
) {
    if !input_handling_res.input_handling_active {
        return;
    }

    for (entity, input, movement) in kcc_qry.iter() {
        if !input.input_handling_active {
            continue;
        }

        // Check if running is allowed based on conditions
        let run_conditions_met = !input.run_conditions.forward_only
            || input
                .forward
                .iter()
                .any(|&key| keyboard_input_res.pressed(key));

        // If conditions not met and currently running, stop running
        if !run_conditions_met {
            if movement.is_running {
                run_event_writer.write(IchunRunEvent {
                    entity,
                    is_running: Some(false),
                });
            }
            continue;
        }

        // Handle toggle mode
        if input.is_running_toggled {
            if input
                .run
                .iter()
                .any(|&key| keyboard_input_res.just_pressed(key))
            {
                run_event_writer.write(IchunRunEvent {
                    entity,
                    is_running: None, // None signals to toggle the current state
                });
            }
            continue;
        }

        // Handle hold-to-run mode
        let run_key_pressed = input.run.iter().any(|&key| keyboard_input_res.pressed(key));

        if movement.is_running != run_key_pressed {
            run_event_writer.write(IchunRunEvent {
                entity,
                is_running: Some(run_key_pressed),
            });
        }
    }
}

fn jump_input_sys(
    mut jump_event_writer: MessageWriter<IchunJumpEvent>,
    keyboard_input_res: Res<ButtonInput<KeyCode>>,
    input_handling_res: Res<InputHandling>,
    kcc_qry: Query<(Entity, &KccInputConfig), With<Kcc>>,
) {
    if !input_handling_res.input_handling_active {
        return;
    }

    for (entity, input) in kcc_qry.iter() {
        if !input.input_handling_active {
            continue;
        }

        let jump_pressed = input
            .jump
            .iter()
            .any(|&key| keyboard_input_res.just_pressed(key));

        if jump_pressed {
            jump_event_writer.write(IchunJumpEvent { entity });
        }
    }
}

fn float_input_sys(
    mut float_event_writer: MessageWriter<IchunFloatEvent>,
    keyboard_input_res: Res<ButtonInput<KeyCode>>,
    input_handling_res: Res<InputHandling>,
    kcc_qry: Query<(Entity, &KccInputConfig, &KccMovementEventsConfig, &Kcc)>,
) {
    if !input_handling_res.input_handling_active {
        return;
    }

    for (entity, input, movement, kcc) in kcc_qry.iter() {
        if !input.input_handling_active {
            continue;
        }

        // If grounded and currently floating, stop running
        if kcc.is_grounded {
            if movement.is_floating {
                float_event_writer.write(IchunFloatEvent {
                    entity,
                    is_floating: Some(false),
                });
            }
            continue;
        }

        // Handle toggle mode
        if input.is_floating_toggled {
            if input
                .float
                .iter()
                .any(|&key| keyboard_input_res.just_pressed(key))
            {
                float_event_writer.write(IchunFloatEvent {
                    entity,
                    is_floating: None, // None signals to toggle the current state
                });
            }
            continue;
        }

        // Handle hold-to-float mode
        let float_key_pressed = input
            .float
            .iter()
            .any(|&key| keyboard_input_res.pressed(key));

        if movement.is_floating != float_key_pressed {
            float_event_writer.write(IchunFloatEvent {
                entity,
                is_floating: Some(float_key_pressed),
            });
        }
    }
}

fn rotation_input_sys(
    mut look_event_writer: MessageWriter<IchunRotateEvent>,
    keyboard_input_res: Res<ButtonInput<KeyCode>>,
    input_handling_res: Res<InputHandling>,
    accumulated_mouse_motion: Res<AccumulatedMouseMotion>,
    kcc_qry: Query<(Entity, &KccInputConfig), With<Kcc>>,
) {
    if !input_handling_res.input_handling_active {
        return;
    }

    let mouse_delta = accumulated_mouse_motion.delta;

    if mouse_delta == Vector2::ZERO {
        return;
    }

    for (entity, input) in kcc_qry.iter() {
        if !input.input_handling_active {
            continue;
        }

        let should_rotate = match &input.rotation_activation {
            Some(activation_keys) => activation_keys
                .iter()
                .any(|&key| keyboard_input_res.pressed(key)),
            None => true,
        };

        if should_rotate {
            look_event_writer.write(IchunRotateEvent {
                entity,
                rotation: mouse_delta,
            });
        }
    }
}