Skip to content

Add Input convenience resource #14

@cart

Description

@cart

Currently consuming input events looks like this:

fn move_on_input(
    world: &mut SubWorld,
    mut state: ResMut<State>,
    time: Res<Time>,
    keyboard_input_events: Res<Events<KeyboardInput>>,
    query: &mut Query<(Write<Translation>, Read<Handle<Mesh>>)>,
) {
    let mut moving_left = false;
    let mut moving_right = false;
    for event in state.event_reader.iter(&keyboard_input_events) {
        if let KeyboardInput {
            virtual_key_code: Some(key_code),
            state,
            ..
        } = event
        {
            if *key_code == VirtualKeyCode::Left {
                moving_left = state.is_pressed();
            } else if *key_code == VirtualKeyCode::Right {
                moving_right = state.is_pressed();
            }
        }
    }

    for (mut translation, _) in query.iter_mut(world) {
        if moving_left {
            translation.0 += math::vec3(1.0, 0.0, 0.0) * time.delta_seconds;
        }

        if moving_right {
            translation.0 += math::vec3(-1.0, 0.0, 0.0) * time.delta_seconds;
        }
    }
}

It would be great if it looked like this instead.

fn move_on_input(
    world: &mut SubWorld,
    mut state: ResMut<State>,
    time: Res<Time>,
    input: Res<Input>,
    query: &mut Query<(Write<Translation>, Read<Handle<Mesh>>)>,
) {
    let mut moving_left = input.key_pressed(VirtualKeyCode::Left);
    let mut moving_right = input.key_pressed(VirtualKeyCode::Right);

    for (mut translation, _) in query.iter_mut(world) {
        if moving_left {
            translation.0 += math::vec3(1.0, 0.0, 0.0) * time.delta_seconds;
        }

        if moving_right {
            translation.0 += math::vec3(-1.0, 0.0, 0.0) * time.delta_seconds;
        }
    }
}

The raw events are a good first step (and shouldnt be removed), but the common "was this input pressed before this update" case should be optimized.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions