Skip to main content

three_d/renderer/control/
first_person_control.rs

1use super::*;
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(
20        &mut self,
21        camera: &mut three_d_asset::Camera,
22        events: &mut [Event],
23    ) -> bool {
24        let mut change = false;
25        for event in events.iter_mut() {
26            match event {
27                Event::MouseMotion {
28                    delta,
29                    button,
30                    handled,
31                    ..
32                } if !*handled && Some(MouseButton::Left) == *button => {
33                    camera.yaw(radians(delta.0 * std::f32::consts::PI / 1800.0));
34                    camera.pitch(radians(delta.1 * std::f32::consts::PI / 1800.0));
35                    *handled = true;
36                    change = true;
37                }
38                Event::MouseWheel { delta, handled, .. } if !*handled => {
39                    let v = camera.view_direction() * self.speed * delta.1;
40                    camera.translate(v);
41                    *handled = true;
42                    change = true;
43                }
44                _ => {}
45            }
46        }
47        change
48    }
49}