three_d/renderer/control/
first_person_control.rs

1use crate::renderer::*;
2
3///
4/// A control that makes the camera move like it is a person on the ground.
5///
6#[derive(Clone, Copy, Debug)]
7pub struct FirstPersonControl {
8    /// The speed of movements.
9    pub speed: f32,
10}
11
12impl FirstPersonControl {
13    /// Creates a new first person control with the given speed of movements.
14    pub fn new(speed: f32) -> Self {
15        Self { speed }
16    }
17
18    /// Handles the events. Must be called each frame.
19    pub fn handle_events(&mut self, camera: &mut Camera, events: &mut [Event]) -> bool {
20        let mut change = false;
21        for event in events.iter_mut() {
22            match event {
23                Event::MouseMotion {
24                    delta,
25                    button,
26                    handled,
27                    ..
28                } => {
29                    if !*handled {
30                        if Some(MouseButton::Left) == *button {
31                            camera.yaw(radians(delta.0 * std::f32::consts::PI / 1800.0));
32                            camera.pitch(radians(delta.1 * std::f32::consts::PI / 1800.0));
33                            *handled = true;
34                            change = true;
35                        }
36                    }
37                }
38                Event::MouseWheel { delta, handled, .. } => {
39                    if !*handled {
40                        let v = camera.view_direction() * self.speed * delta.1;
41                        camera.translate(v);
42                        *handled = true;
43                        change = true;
44                    }
45                }
46                _ => {}
47            }
48        }
49        change
50    }
51}