Struct pixel_game_lib::window::Input

source ·
pub struct Input { /* private fields */ }
Expand description

Re-export winit_input_helper type. The main struct of the API.

Create with WinitInputHelper::new. Call WinitInputHelper::update for every winit::event::Event you receive from winit. WinitInputHelper::update returning true indicates a step has occured. You should now run your application logic, calling any of the accessor methods you need.

An alternative API is provided via WinitInputHelper::step_with_window_events, call this method instead of WinitInputHelper::update if you need to manually control when a new step begins. A step occurs every time this method is called.

Do not mix usages of WinitInputHelper::update and WinitInputHelper::step_with_window_events. You should stick to one or the other.

Implementations§

source§

impl WinitInputHelper

source

pub fn new() -> WinitInputHelper

source

pub fn update<T>(&mut self, event: &Event<T>) -> bool

Pass every winit event to this function and run your application logic when it returns true.

The following winit events are handled:

  • Event::NewEvents clears all internal state.
  • Event::MainEventsCleared causes this function to return true, signifying a “step” has completed.
  • Event::WindowEvent updates internal state, this will affect the result of accessor methods immediately.
  • Event::DeviceEvent updates value of mouse_diff()
source

pub fn step_with_window_events(&mut self, events: &[WindowEvent])

Pass a slice containing every winit event that occured within the step to this function. Ensure this method is only called once per application main loop. Ensure every event since the last WinitInputHelper::step_with_window_events call is included in the events argument.

WinitInputHelper::Update is easier to use. But this method is useful when your application logic steps dont line up with winit’s event loop. e.g. you have a seperate thread for application logic using WinitInputHelper that constantly runs regardless of winit’s event loop and you need to send events to it directly.

source

pub fn key_pressed(&self, keycode: KeyCode) -> bool

Returns true when the key with the specified keycode goes from “not pressed” to “pressed”. Otherwise returns false.

Uses physical keys in the US layout, so for example the W key will be in the same physical key on both US and french keyboards.

This is suitable for game controls.

Examples found in repository?
examples/window.rs (line 26)
19
20
21
22
23
24
25
26
27
    fn update(&mut self, input: &Input, _mouse_pos: Option<Vec2<usize>>, _dt: f32) -> bool {
        // Increment when mouse is clicked
        if input.mouse_held(MouseButton::Left) {
            self.pixels_to_draw += 1;
        }

        // Exit when escape is pressed
        input.key_pressed(KeyCode::Escape)
    }
More examples
Hide additional examples
examples/font.rs (line 36)
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
fn main() {
    // Window configuration with default pixel size and scaling
    let window_config = WindowConfig {
        ..Default::default()
    };

    // Load a font for the widgets
    let font = font();

    // Open the window and start the game-loop
    pixel_game_lib::window(
        // We don't use any state so we pass a zero-sized type
        (),
        window_config.clone(),
        // Update loop exposing input events we can handle, this is where you would handle the game logic
        |_state, input, _mouse, _dt| {
            // Exit when escape is pressed
            input.key_pressed(KeyCode::Escape)
        },
        // Render loop exposing the pixel buffer we can mutate
        move |_state, canvas, _dt| {
            // Draw the text at the center of the screen
            font.render_centered(
                "pixel-game-lib font example",
                Vec2::new(
                    window_config.buffer_size.w / 2,
                    window_config.buffer_size.h / 2,
                )
                .as_(),
                canvas,
            );
        },
    )
    .expect("Error opening window");
}
examples/draw.rs (line 29)
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
fn main() {
    // Window configuration with huge pixels
    let window_config = WindowConfig {
        buffer_size: Extent2::new(64, 64),
        scaling: 8,
        ..Default::default()
    };

    // Open the window and start the game-loop
    pixel_game_lib::window(
        // Keep track of the mouse as our "game state"
        Vec2::zero(),
        window_config.clone(),
        // Update loop exposing input events we can handle, this is where you would handle the game logic
        |state, input, mouse, _dt| {
            // Set the mouse position as the game state
            if let Some(mouse) = mouse {
                *state = mouse;
            }

            // Exit when escape is pressed
            input.key_pressed(KeyCode::Escape)
        },
        // Render loop exposing the pixel buffer we can mutate
        move |mouse, canvas, _dt| {
            // Reset the canvas with a white color
            canvas.fill(0xFFFFFFFF);

            // Draw a gray circle with the radius being the distance of the center to the mouse
            let circle_center = Vec2::new(50.0, 50.0);
            let dist_from_mouse = mouse.as_().distance(circle_center);
            canvas.draw_circle(Disk::new(circle_center, dist_from_mouse), 0xFF999999);
            // Draw a darker gray circle outline on top of the circle
            canvas.draw_circle_outline(Disk::new(circle_center, dist_from_mouse), 0xFF333333);

            // Draw a light green blue triangle with one corner being snapped to the mouse
            canvas.draw_triangle(
                [Vec2::new(45.0, 5.0), Vec2::new(60.0, 8.0), mouse.as_()],
                0xFF99FF99,
            );

            // Draw a light blue quadrilateral with one corner being snapped to the mouse
            canvas.draw_quad(
                [
                    Vec2::new(5.0, 5.0),
                    Vec2::new(20.0, 8.0),
                    Vec2::new(8.0, 30.0),
                    mouse.as_(),
                ],
                0xFF9999FF,
            );

            // Draw a black line from the center of the canvas to our mouse
            canvas.draw_line(
                (window_config.buffer_size.as_() / 2.0).into(),
                mouse.as_(),
                0xFF000000,
            );

            // Draw a red pixel under the mouse
            canvas.set_pixel(mouse.as_(), 0xFFFF0000);
        },
    )
    .expect("Error opening window");
}
source

pub fn key_pressed_os(&self, keycode: KeyCode) -> bool

Returns true when the key with the specified keycode goes from “not pressed” to “pressed”. Otherwise returns false.

Uses physical keys in the US layout, so for example the W key will be in the same physical key on both US and french keyboards.

Will repeat key presses while held down according to the OS’s key repeat configuration This is suitable for UI.

source

pub fn key_released(&self, keycode: KeyCode) -> bool

Returns true when the key with the specified KeyCode goes from “pressed” to “not pressed”. Otherwise returns false.

Uses physical keys in the US layout, so for example the W key will be in the same physical key on both US and french keyboards.

source

pub fn key_held(&self, keycode: KeyCode) -> bool

Returns true when the key with the specified keycode remains “pressed”. Otherwise returns false.

Uses physical keys in the US layout, so for example the W key will be in the same physical key on both US and french keyboards.

source

pub fn held_shift(&self) -> bool

Returns true while any shift key is held on the keyboard. Otherwise returns false.

Uses physical keys.

source

pub fn held_control(&self) -> bool

Returns true while any control key is held on the keyboard. Otherwise returns false.

Uses physical keys.

source

pub fn held_alt(&self) -> bool

Returns true while any alt key is held on the keyboard. Otherwise returns false.

Uses physical keys.

source

pub fn key_pressed_logical(&self, check_key: Key<&str>) -> bool

Returns true when the specified keyboard key goes from “not pressed” to “pressed”. Otherwise returns false.

Uses logical keypresses, so for example W is changed between a US and french keyboard. Will never repeat keypresses while held.

source

pub fn key_pressed_os_logical(&self, check_key: Key<&str>) -> bool

Returns true when the specified keyboard key goes from “not pressed” to “pressed”. Otherwise returns false.

Uses logical keypresses, so for example W is changed between a US and french keyboard.

Will repeat key presses while held down according to the OS’s key repeat configuration This is suitable for UI.

source

pub fn key_released_logical(&self, check_key: Key<&str>) -> bool

Returns true when the specified keyboard key goes from “pressed” to “not pressed”. Otherwise returns false.

Uses logical keypresses, so for example W is changed between a US and french keyboard.

source

pub fn key_held_logical(&self, check_key: Key<&str>) -> bool

Returns true while the specified keyboard key remains “pressed”. Otherwise returns false.

Uses logical keypresses, so for example W is changed between a US and french keyboard.

source

pub fn mouse_pressed(&self, mouse_button: MouseButton) -> bool

Returns true when the specified mouse button goes from “not pressed” to “pressed”. Otherwise returns false.

source

pub fn mouse_released(&self, mouse_button: MouseButton) -> bool

Returns true when the specified mouse button goes from “pressed” to “not pressed”. Otherwise returns false.

source

pub fn mouse_held(&self, mouse_button: MouseButton) -> bool

Returns true while the specified mouse button remains “pressed”. Otherwise returns false.

Examples found in repository?
examples/window.rs (line 21)
19
20
21
22
23
24
25
26
27
    fn update(&mut self, input: &Input, _mouse_pos: Option<Vec2<usize>>, _dt: f32) -> bool {
        // Increment when mouse is clicked
        if input.mouse_held(MouseButton::Left) {
            self.pixels_to_draw += 1;
        }

        // Exit when escape is pressed
        input.key_pressed(KeyCode::Escape)
    }
source

pub fn scroll_diff(&self) -> (f32, f32)

Returns (0.0, 0.0) when the window is not focused. Otherwise returns the amount scrolled by the mouse during the last step. Returns (horizontally, vertically)

source

pub fn cursor(&self) -> Option<(f32, f32)>

Returns the cursor coordinates in pixels, when window is focused AND (cursor is on window OR any mouse button remains held while cursor moved off window) Otherwise returns None

source

pub fn cursor_diff(&self) -> (f32, f32)

Returns the change in cursor coordinates that occured during the last step, when window is focused AND (cursor is on window OR any mouse button remains held while cursor moved off window) Otherwise returns (0.0, 0.0).

source

pub fn mouse_diff(&self) -> (f32, f32)

Returns the change in mouse coordinates that occured during the last step.

This is useful when implementing first person controls with a captured mouse.

Because this uses DeviceEvents, the step_with_windows_events function won’t update this as it is not a WindowEvent.

source

pub fn text(&self) -> &[Key]

Returns the characters pressed during the last step. The characters are in the order they were pressed.

source

pub fn dropped_file(&self) -> Option<PathBuf>

Returns the path to a file that has been drag-and-dropped onto the window.

source

pub fn window_resized(&self) -> Option<PhysicalSize<u32>>

Returns the current window size if it was resized during the last step. Otherwise returns None.

source

pub fn resolution(&self) -> Option<(u32, u32)>

Returns None when no WindowEvent::Resized have been received yet. After one has been received it returns the current resolution of the window.

source

pub fn scale_factor_changed(&self) -> Option<f64>

Returns the current scale factor if it was changed during the last step. Otherwise returns None.

source

pub fn scale_factor(&self) -> Option<f64>

Returns None when no WindowEvent::ScaleFactorChanged have been received yet. After one has been received it returns the current scale_factor of the window.

source

pub fn destroyed(&self) -> bool

Returns true if the window has been destroyed Otherwise returns false. Once this method has returned true once all following calls to this method will also return true.

source

pub fn close_requested(&self) -> bool

Returns true if the OS has requested the application to close during this step. Otherwise returns false.

source

pub fn delta_time(&self) -> Option<Duration>

Returns the std::time::Duration elapsed since the last step. Returns None if the step is still in progress.

Trait Implementations§

source§

impl Clone for WinitInputHelper

source§

fn clone(&self) -> WinitInputHelper

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Default for WinitInputHelper

source§

fn default() -> WinitInputHelper

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> Downcast<T> for T

source§

fn downcast(&self) -> &T

source§

impl<T> Downcast for T
where T: Any,

source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
source§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Send + Sync>

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> IntoEither for T

source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

impl<T> Pointable for T

source§

const ALIGN: usize = _

The alignment of pointer.
§

type Init = T

The type for initializers.
source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
source§

impl<R, P> ReadPrimitive<R> for P
where R: Read + ReadEndian<P>, P: Default,

source§

fn read_from_little_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_little_endian().
source§

fn read_from_big_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_big_endian().
source§

fn read_from_native_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_native_endian().
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
source§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
source§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<T> Upcast<T> for T

source§

fn upcast(&self) -> Option<&T>

source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

impl<T> Component for T
where T: Send + Sync + 'static,