aboutsummaryrefslogtreecommitdiff
path: root/games/rstnode/rst-client/src/input.rs
blob: 83ae17286d612f5d9d4acc623fa159217fc0e260 (plain)
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
//! Advanced input handler

use crate::{graphics::Vector2, viewport::Viewport};
use ggez::{
    event::EventHandler,
    input::mouse::{self, MouseButton},
    Context, GameResult,
};

pub struct InputHandle {
    /// The mouse position on the viewport
    pub mouse_pos: Vector2,
    /// Whether the left mouse button is pressed this frame
    pub left_pressed: bool,
    /// Whether the middle mouse button is pressed this frame
    pub middle_pressed: bool,
    /// Whether the right mouse button is pressed this frame
    pub right_pressed: bool,
    /// Set when pressing left mouse and unset when releasing it
    pub drag_point: Option<Vector2>,
    /// Get the scroll-wheel position this frame
    pub scroll_offset: f32,
}

impl InputHandle {
    pub fn new() -> Self {
        Self {
            mouse_pos: Vector2::new(0.0, 0.0),
            left_pressed: false,
            middle_pressed: false,
            right_pressed: false,
            drag_point: None,
            scroll_offset: 1.0,
        }
    }

    /// Get the unprojected mouse coordinates
    pub fn unproject(&self, vp: &Viewport) -> Vector2 {
        // self.mouse_pos.clone() - vp.start().clone()

        todo!()
    }
}

impl EventHandler for InputHandle {
    fn update(&mut self, ctx: &mut Context) -> GameResult<()> {
        self.mouse_pos = mouse::position(&ctx).into();
        self.left_pressed = mouse::button_pressed(ctx, MouseButton::Left);
        self.middle_pressed = mouse::button_pressed(ctx, MouseButton::Middle);
        self.right_pressed = mouse::button_pressed(ctx, MouseButton::Right);

        // Only set the drag_point once and unset when we release Left button
        if self.middle_pressed && self.drag_point.is_none() {
            self.drag_point = Some(self.mouse_pos.clone());
        } else if !self.middle_pressed {
            self.drag_point = None;
        }

        Ok(())
    }

    fn mouse_wheel_event(&mut self, _ctx: &mut Context, _: f32, y: f32) {
        self.scroll_offset -= y * 0.25;
    }

    fn draw(&mut self, _: &mut Context) -> GameResult<()> {
        panic!("Don't draw the input handle!");
    }
}