bevy/examples/input/keyboard_input.rs

80 lines
2.3 KiB
Rust
Raw Normal View History

2020-06-05 06:49:36 +00:00
use bevy::{
input::{keyboard::KeyCode, Input},
prelude::*,
};
2020-04-04 21:59:49 +00:00
fn main() {
App::build()
.add_default_plugins()
2020-05-14 00:31:56 +00:00
.add_startup_system(setup.system())
.add_system(move_on_input.system())
2020-04-04 21:59:49 +00:00
.run();
}
2020-06-05 06:49:36 +00:00
/// This system moves our cube left when the "left" key is pressed and moves it right when the "right" key is pressed
2020-05-14 00:31:56 +00:00
fn move_on_input(
2020-06-05 02:47:27 +00:00
world: &mut SubWorld,
2020-05-14 00:52:47 +00:00
time: Res<Time>,
keyboard_input: Res<Input<KeyCode>>,
2020-06-05 02:47:27 +00:00
query: &mut Query<(Write<Translation>, Read<Handle<Mesh>>)>,
) {
let moving_left = keyboard_input.pressed(KeyCode::Left);
let moving_right = keyboard_input.pressed(KeyCode::Right);
if keyboard_input.just_pressed(KeyCode::Left) {
println!("left just pressed");
}
if keyboard_input.just_released(KeyCode::Left) {
println!("left just released");
}
2020-04-04 21:59:49 +00:00
let speed = 3.0;
2020-06-05 02:47:27 +00:00
for (mut translation, _) in query.iter_mut(world) {
if moving_left {
translation.0 += math::vec3(speed, 0.0, 0.0) * time.delta_seconds;
2020-06-05 02:47:27 +00:00
}
if moving_right {
translation.0 += math::vec3(-speed, 0.0, 0.0) * time.delta_seconds;
2020-06-05 02:47:27 +00:00
}
}
2020-04-04 21:59:49 +00:00
}
2020-06-05 06:49:36 +00:00
/// Creates a simple scene containing the cube we will be controlling
2020-05-14 00:31:56 +00:00
fn setup(
command_buffer: &mut CommandBuffer,
2020-05-14 00:52:47 +00:00
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
2020-05-14 00:31:56 +00:00
) {
2020-05-16 07:21:04 +00:00
let cube_handle = meshes.add(Mesh::from(shape::Cube { size: 1.0 }));
2020-05-13 23:42:27 +00:00
let cube_material_handle = materials.add(StandardMaterial {
2020-04-04 21:59:49 +00:00
albedo: Color::rgb(0.5, 0.4, 0.3),
..Default::default()
});
2020-05-14 00:31:56 +00:00
command_buffer
2020-04-04 21:59:49 +00:00
.build()
// cube
.add_entity(MeshEntity {
mesh: cube_handle,
material: cube_material_handle,
translation: Translation::new(0.0, 0.0, 1.0),
..Default::default()
})
// light
.add_entity(LightEntity {
translation: Translation::new(4.0, -4.0, 5.0),
..Default::default()
})
// camera
.add_entity(PerspectiveCameraEntity {
local_to_world: LocalToWorld::new_sync_disabled(Mat4::look_at_rh(
2020-06-05 06:49:36 +00:00
Vec3::new(0.0, 8.0, 5.0),
2020-04-04 21:59:49 +00:00
Vec3::new(0.0, 0.0, 0.0),
Vec3::new(0.0, 0.0, 1.0),
)),
..Default::default()
2020-04-07 20:25:01 +00:00
});
2020-04-04 21:59:49 +00:00
}