Keyboard Input
Keyboard input events can be handled by listening to WindowEvent::KeyboardInput
, for example you can check for A, D
keys and save their state in some variables in your script. These variables will tell the script that an entity, to
which the script was assigned, should move in a certain direction. This could be expressed like so:
#![allow(unused)] fn main() { #[derive(Clone, Debug, Reflect, Visit, TypeUuidProvider, ComponentProvider)] #[type_uuid(id = "abbad54c-e267-4d7e-a3cd-e125a7e87ff0")] #[visit(optional)] pub struct Player { move_left: bool, move_right: bool, } impl ScriptTrait for Player { fn on_os_event(&mut self, event: &Event<()>, _ctx: &mut ScriptContext) { // Listen to keyboard events, that comes to the main window. if let Event::WindowEvent { event: WindowEvent::KeyboardInput { event, .. }, .. } = event { let pressed = event.state == ElementState::Pressed; if let PhysicalKey::Code(code) = event.physical_key { // Check which key was pressed and remember this state for further usage. match code { KeyCode::KeyA => { self.move_left = pressed; } KeyCode::KeyD => { self.move_right = pressed; } _ => (), } } } } fn on_update(&mut self, ctx: &mut ScriptContext) { let node = &mut ctx.scene.graph[ctx.handle]; let transform = node.local_transform_mut(); if self.move_left { transform.offset(Vector3::new(-1.0, 0.0, 0.0)); } if self.move_right { transform.offset(Vector3::new(1.0, 0.0, 0.0)); } } } }
The main method here is on_os_event
, which listens for keyboard events and modifies script variables accordingly.
These two variables are then used in the on_update
method to move the entity, to which the script is assigned to.