-1

Consider a simple component representing the player struct TilePos(i32, i32); and spawned as commands.spawn((TilePos(0, 0), ));.

What's the correct way of reacting to keyboard input, e.g. the arrow keys, and change TilePos by one whenever a key is pressed once?

Jakub Arnold
  • 85,596
  • 89
  • 230
  • 327

1 Answers1

2

You probably want to look at the cookbook for more examples.

If there is only one player, then you should make it a resource so that you can just do: ResMut<TilePos> in the function definition.

Otherwise you can do:

#[derive(Default)]
struct State {
    event_reader: EventReader<KeyboardInput>,
}

/// This system prints out all keyboard events as they come in
fn print_keyboard_event_system(
    mut state: Local<State>,
    keyboard_input_events: Res<Events<KeyboardInput>>,
    mut query: Query<&mut TilePos>
) {
    for event in state.event_reader.iter(&keyboard_input_events) {
        if event.state == bevy::input::ElementState::Pressed && event.key_code == Some(bevy::input::keyboard::KeyCode::Up){
            for mut t in &mut query.iter_mut() {
                t.1 += 1;
                println!("New Tile: {} {}", t.0, t.1);
                println!("{:?}", event);
            }
        }
    }
}

If you were wanting to edit a specific tile, then you could spawn it with another component (.with()) and make the query more specific with Query<TilePos, With<Specific>>.

This code is adapted from here.

Will
  • 1,059
  • 2
  • 10
  • 22