bevy_archie 0.3.0

A comprehensive game controller support module for Bevy
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
//! Touch-screen virtual joystick for mobile and touchpad controls.
//!
//! This module provides a virtual joystick that can be rendered on screen
//! and controlled via touch input, perfect for mobile games or touchpad controls.
//!
//! # Example
//!
//! ```rust,no_run
//! use bevy::prelude::*;
//! use bevy_archie::touch_joystick::{TouchJoystick, TouchJoystickPlugin, TouchJoystickSettings};
//!
//! App::new()
//!     .add_plugins(DefaultPlugins)
//!     .add_plugins(TouchJoystickPlugin)
//!     .add_systems(Startup, setup)
//!     .run();
//!
//! fn setup(mut commands: Commands) {
//!     commands.spawn(TouchJoystick::left());
//! }
//! ```

use bevy::prelude::*;
use serde::{Deserialize, Serialize};

/// Plugin for touch-screen virtual joystick functionality.
pub struct TouchJoystickPlugin;

impl Plugin for TouchJoystickPlugin {
    fn build(&self, app: &mut App) {
        app.register_type::<TouchJoystick>()
            .register_type::<TouchJoystickSettings>()
            .init_resource::<TouchJoystickSettings>()
            .add_message::<TouchJoystickEvent>()
            .add_systems(
                Update,
                (update_touch_joysticks, emit_joystick_events).chain_ignore_deferred(),
            );
    }
}

/// A virtual joystick component for touch input.
#[derive(Component, Debug, Clone, Reflect)]
pub struct TouchJoystick {
    /// Base position of the joystick (center of the base)
    pub base_position: Vec2,
    /// Current position of the knob relative to base
    pub knob_offset: Vec2,
    /// Maximum distance the knob can travel from the base
    pub radius: f32,
    /// Deadzone as a percentage of radius (0.0 to 1.0)
    pub deadzone: f32,
    /// Whether this joystick is currently being touched
    pub active: bool,
    /// The touch ID currently controlling this joystick
    pub touch_id: Option<u64>,
    /// Which side of the screen this joystick is on
    pub side: JoystickSide,
    /// Whether the base follows the initial touch
    pub floating: bool,
    /// Whether to snap back to center on release
    pub snap_to_center: bool,
}

impl Default for TouchJoystick {
    fn default() -> Self {
        Self {
            base_position: Vec2::ZERO,
            knob_offset: Vec2::ZERO,
            radius: 100.0,
            deadzone: 0.1,
            active: false,
            touch_id: None,
            side: JoystickSide::Left,
            floating: true,
            snap_to_center: true,
        }
    }
}

impl TouchJoystick {
    /// Create a left-side joystick (common for movement).
    #[must_use]
    pub fn left() -> Self {
        Self {
            side: JoystickSide::Left,
            ..Default::default()
        }
    }

    /// Create a right-side joystick (common for camera/aiming).
    #[must_use]
    pub fn right() -> Self {
        Self {
            side: JoystickSide::Right,
            ..Default::default()
        }
    }

    /// Create a joystick at a fixed position.
    #[must_use]
    pub fn fixed(position: Vec2) -> Self {
        Self {
            base_position: position,
            floating: false,
            ..Default::default()
        }
    }

    /// Set the radius.
    #[must_use]
    pub fn with_radius(mut self, radius: f32) -> Self {
        self.radius = radius;
        self
    }

    /// Set the deadzone.
    #[must_use]
    pub fn with_deadzone(mut self, deadzone: f32) -> Self {
        self.deadzone = deadzone.clamp(0.0, 1.0);
        self
    }

    /// Get the normalized axis value (-1 to 1 for each component).
    #[must_use]
    pub fn axis(&self) -> Vec2 {
        if !self.active {
            return Vec2::ZERO;
        }

        let magnitude = self.knob_offset.length() / self.radius;
        if magnitude < self.deadzone {
            return Vec2::ZERO;
        }

        // Apply deadzone and normalize
        let adjusted_magnitude = (magnitude - self.deadzone) / (1.0 - self.deadzone);
        let direction = self.knob_offset.normalize_or_zero();
        direction * adjusted_magnitude.min(1.0)
    }

    /// Get the raw axis value without deadzone processing.
    #[must_use]
    pub fn raw_axis(&self) -> Vec2 {
        if !self.active {
            return Vec2::ZERO;
        }
        self.knob_offset / self.radius
    }

    /// Get the distance from center as a percentage (0 to 1).
    #[must_use]
    pub fn magnitude(&self) -> f32 {
        (self.knob_offset.length() / self.radius).min(1.0)
    }

    /// Get the angle of the joystick in radians (0 = right, PI/2 = up).
    #[must_use]
    pub fn angle(&self) -> f32 {
        self.knob_offset.y.atan2(self.knob_offset.x)
    }

    /// Check if the joystick is outside the deadzone.
    #[must_use]
    pub fn is_active(&self) -> bool {
        self.active && self.magnitude() > self.deadzone
    }
}

/// Which side of the screen the joystick should respond to.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, Reflect)]
pub enum JoystickSide {
    /// Left half of the screen
    #[default]
    Left,
    /// Right half of the screen
    Right,
    /// Entire screen (only one joystick)
    Full,
    /// Custom zone (use with fixed position)
    Custom,
}

/// Global settings for touch joysticks.
#[derive(Resource, Debug, Clone, Reflect)]
pub struct TouchJoystickSettings {
    /// Default radius for new joysticks
    pub default_radius: f32,
    /// Default deadzone
    pub default_deadzone: f32,
    /// Opacity of the joystick visuals (0.0 to 1.0)
    pub opacity: f32,
    /// Whether to show visual feedback
    pub show_visuals: bool,
    /// Color of the joystick base
    pub base_color: Color,
    /// Color of the joystick knob
    pub knob_color: Color,
    /// Margin from screen edge for floating joysticks
    pub screen_margin: f32,
}

impl Default for TouchJoystickSettings {
    fn default() -> Self {
        Self {
            default_radius: 100.0,
            default_deadzone: 0.1,
            opacity: 0.5,
            show_visuals: true,
            base_color: Color::srgba(0.3, 0.3, 0.3, 0.5),
            knob_color: Color::srgba(0.8, 0.8, 0.8, 0.7),
            screen_margin: 50.0,
        }
    }
}

/// Event emitted when a joystick value changes.
#[derive(Event, Message, Debug, Clone)]
pub struct TouchJoystickEvent {
    /// The entity of the joystick
    pub entity: Entity,
    /// The side of the joystick
    pub side: JoystickSide,
    /// The normalized axis value
    pub axis: Vec2,
    /// Whether the joystick is currently active
    pub active: bool,
    /// The raw offset from center
    pub raw_offset: Vec2,
}

/// System to update touch joysticks based on touch input.
fn update_touch_joysticks(
    touches: Res<Touches>,
    windows: Query<&Window>,
    mut joysticks: Query<&mut TouchJoystick>,
) {
    let Ok(window) = windows.single() else {
        return;
    };
    let window_size = Vec2::new(window.width(), window.height());
    let half_width = window_size.x / 2.0;

    for mut joystick in &mut joysticks {
        // Check if our current touch is still active
        if let Some(touch_id) = joystick.touch_id {
            if let Some(touch) = touches.get_pressed(touch_id) {
                // Update knob position
                let touch_pos = touch.position();
                let offset = touch_pos - joystick.base_position;
                let clamped_offset = if offset.length() > joystick.radius {
                    offset.normalize() * joystick.radius
                } else {
                    offset
                };
                joystick.knob_offset = clamped_offset;
            } else {
                // Touch released
                joystick.active = false;
                joystick.touch_id = None;
                if joystick.snap_to_center {
                    joystick.knob_offset = Vec2::ZERO;
                }
            }
        } else {
            // Look for new touches
            for touch in touches.iter_just_pressed() {
                let touch_pos = touch.position();

                // Check if this touch is in our zone
                let in_zone = match joystick.side {
                    JoystickSide::Left => touch_pos.x < half_width,
                    JoystickSide::Right => touch_pos.x >= half_width,
                    JoystickSide::Full => true,
                    JoystickSide::Custom => {
                        let distance = (touch_pos - joystick.base_position).length();
                        distance <= joystick.radius * 2.0
                    }
                };

                if in_zone {
                    joystick.active = true;
                    joystick.touch_id = Some(touch.id());

                    if joystick.floating {
                        joystick.base_position = touch_pos;
                    }
                    joystick.knob_offset = Vec2::ZERO;
                    break;
                }
            }
        }
    }
}

/// System to emit joystick events.
fn emit_joystick_events(
    joysticks: Query<(Entity, &TouchJoystick), Changed<TouchJoystick>>,
    mut events: MessageWriter<TouchJoystickEvent>,
) {
    for (entity, joystick) in &joysticks {
        events.write(TouchJoystickEvent {
            entity,
            side: joystick.side,
            axis: joystick.axis(),
            active: joystick.is_active(),
            raw_offset: joystick.knob_offset,
        });
    }
}

/// Convenience component to render a basic joystick visual.
#[derive(Component, Debug, Clone)]
pub struct TouchJoystickVisual {
    /// Entity of the joystick this visual represents
    pub joystick_entity: Entity,
}

/// System to spawn visual elements for a joystick.
pub fn spawn_joystick_visual(
    commands: &mut Commands,
    settings: &TouchJoystickSettings,
    joystick_entity: Entity,
    joystick: &TouchJoystick,
) -> Entity {
    let base_entity = commands
        .spawn((
            Sprite {
                color: settings.base_color.with_alpha(settings.opacity),
                custom_size: Some(Vec2::splat(joystick.radius * 2.0)),
                ..default()
            },
            Transform::from_translation(joystick.base_position.extend(0.0)),
            TouchJoystickVisual { joystick_entity },
        ))
        .id();

    // Spawn knob as child
    commands.entity(base_entity).with_children(|parent| {
        parent.spawn((
            Sprite {
                color: settings.knob_color.with_alpha(settings.opacity),
                custom_size: Some(Vec2::splat(joystick.radius * 0.6)),
                ..default()
            },
            Transform::default(),
        ));
    });

    base_entity
}

/// Cardinal direction based on joystick angle.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum JoystickDirection {
    /// No direction (in deadzone)
    None,
    /// Up
    Up,
    /// Down
    Down,
    /// Left
    Left,
    /// Right
    Right,
    /// Up-Left diagonal
    UpLeft,
    /// Up-Right diagonal
    UpRight,
    /// Down-Left diagonal
    DownLeft,
    /// Down-Right diagonal
    DownRight,
}

impl TouchJoystick {
    /// Get the cardinal direction of the joystick (8-way).
    #[must_use]
    pub fn direction_8way(&self) -> JoystickDirection {
        if !self.is_active() {
            return JoystickDirection::None;
        }

        let angle = self.angle();
        let pi = std::f32::consts::PI;

        // 8 directions, each covering 45 degrees
        if angle > -pi / 8.0 && angle <= pi / 8.0 {
            JoystickDirection::Right
        } else if angle > pi / 8.0 && angle <= 3.0 * pi / 8.0 {
            JoystickDirection::UpRight
        } else if angle > 3.0 * pi / 8.0 && angle <= 5.0 * pi / 8.0 {
            JoystickDirection::Up
        } else if angle > 5.0 * pi / 8.0 && angle <= 7.0 * pi / 8.0 {
            JoystickDirection::UpLeft
        } else if angle > 7.0 * pi / 8.0 || angle <= -7.0 * pi / 8.0 {
            JoystickDirection::Left
        } else if angle > -7.0 * pi / 8.0 && angle <= -5.0 * pi / 8.0 {
            JoystickDirection::DownLeft
        } else if angle > -5.0 * pi / 8.0 && angle <= -3.0 * pi / 8.0 {
            JoystickDirection::Down
        } else {
            JoystickDirection::DownRight
        }
    }

    /// Get the cardinal direction of the joystick (4-way).
    #[must_use]
    pub fn direction_4way(&self) -> JoystickDirection {
        if !self.is_active() {
            return JoystickDirection::None;
        }

        let angle = self.angle();
        let pi = std::f32::consts::PI;

        // 4 directions, each covering 90 degrees
        if angle > -pi / 4.0 && angle <= pi / 4.0 {
            JoystickDirection::Right
        } else if angle > pi / 4.0 && angle <= 3.0 * pi / 4.0 {
            JoystickDirection::Up
        } else if angle > 3.0 * pi / 4.0 || angle <= -3.0 * pi / 4.0 {
            JoystickDirection::Left
        } else {
            JoystickDirection::Down
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_joystick_creation() {
        let left = TouchJoystick::left();
        assert_eq!(left.side, JoystickSide::Left);

        let right = TouchJoystick::right();
        assert_eq!(right.side, JoystickSide::Right);
    }

    #[test]
    fn test_joystick_axis() {
        let mut joystick = TouchJoystick::default();
        joystick.active = true;
        joystick.radius = 100.0;
        joystick.deadzone = 0.1;

        // Inside deadzone
        joystick.knob_offset = Vec2::new(5.0, 0.0);
        assert_eq!(joystick.axis(), Vec2::ZERO);

        // Outside deadzone
        joystick.knob_offset = Vec2::new(50.0, 0.0);
        let axis = joystick.axis();
        assert!(axis.x > 0.0);
        assert!((axis.y).abs() < 0.001);
    }

    #[test]
    fn test_joystick_direction() {
        let mut joystick = TouchJoystick::default();
        joystick.active = true;
        joystick.radius = 100.0;
        joystick.deadzone = 0.0;

        joystick.knob_offset = Vec2::new(50.0, 0.0);
        assert_eq!(joystick.direction_4way(), JoystickDirection::Right);

        joystick.knob_offset = Vec2::new(0.0, 50.0);
        assert_eq!(joystick.direction_4way(), JoystickDirection::Up);

        joystick.knob_offset = Vec2::new(-50.0, 0.0);
        assert_eq!(joystick.direction_4way(), JoystickDirection::Left);

        joystick.knob_offset = Vec2::new(0.0, -50.0);
        assert_eq!(joystick.direction_4way(), JoystickDirection::Down);
    }

    #[test]
    fn test_joystick_magnitude() {
        let mut joystick = TouchJoystick::default();
        joystick.active = true;
        joystick.radius = 100.0;

        joystick.knob_offset = Vec2::new(50.0, 0.0);
        assert!((joystick.magnitude() - 0.5).abs() < 0.001);

        joystick.knob_offset = Vec2::new(100.0, 0.0);
        assert!((joystick.magnitude() - 1.0).abs() < 0.001);

        // Clamped to 1.0
        joystick.knob_offset = Vec2::new(150.0, 0.0);
        assert!((joystick.magnitude() - 1.0).abs() < 0.001);
    }
}