~starkingdoms/starkingdoms

ref: e2c74ff0a4af609afb2869c59835838dd76f639c starkingdoms/crates/unified/src/client/input/mod.rs -rw-r--r-- 2.0 KiB
e2c74ff0 — core Revert "aaa ??? ?? ? ?? ???????????????????????????????????????????? i would like to explosion" 10 days ago
                                                                                
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
pub mod util;

use bevy::app::{App, Update};
use bevy::window::PrimaryWindow;
use leafwing_input_manager::Actionlike;
use leafwing_input_manager::input_map::InputMap;
use leafwing_input_manager::prelude::ActionState;
use crate::ecs::MainCamera;
use crate::prelude::*;

#[derive(Actionlike, PartialEq, Eq, Hash, Clone, Copy, Debug, Reflect)]
pub enum ClientAction {
    ThrustForward,
    ThrustBackward,
    ThrustRight,
    ThrustLeft,
    TorqueCw,
    TorqueCcw
}

pub fn input_plugin(app: &mut App) {
    app
        .insert_resource(CursorWorldCoordinates(None))
        .insert_resource(InputMap::new([
            (ClientAction::ThrustForward, KeyCode::KeyW),
            (ClientAction::ThrustForward, KeyCode::ArrowUp),

            (ClientAction::ThrustBackward, KeyCode::KeyS),
            (ClientAction::ThrustBackward, KeyCode::ArrowDown),

            (ClientAction::ThrustLeft, KeyCode::KeyQ),
            // TODO: Shift+left
            (ClientAction::ThrustRight, KeyCode::KeyE),
            // TODO: Shift+right

            (ClientAction::TorqueCw, KeyCode::KeyD),
            (ClientAction::TorqueCw, KeyCode::ArrowRight),

            (ClientAction::TorqueCcw, KeyCode::KeyA),
            (ClientAction::TorqueCcw, KeyCode::ArrowLeft),
        ]))
        .init_resource::<ActionState<ClientAction>>()
        .add_systems(Update, update_cursor_position);
}

#[derive(Resource, Default)]
pub struct CursorWorldCoordinates(pub Option<Vec2>);

fn update_cursor_position(
    q_windows: Query<&Window, With<PrimaryWindow>>,
    q_camera: Query<(&Camera, &GlobalTransform), With<MainCamera>>,
    mut coords: ResMut<CursorWorldCoordinates>,
) {
    let (camera, camera_transform) = q_camera.single().unwrap();
    let window = q_windows.single().unwrap();

    if let Some(world_position) = window
        .cursor_position()
        .and_then(|cursor| camera.viewport_to_world(camera_transform, cursor).ok())
        .map(|ray| ray.origin.truncate())
    {
        coords.0 = Some(world_position);
    } else {
        coords.0 = None;
    }
}