Latest commit 0f209fc
键盘输入
相关的官方文档:[keyboard_input]、[keyboard_input_events]
检查某个键的状态
检查某个键的状态(按下或释放)目前只能通过键码(Key Code)来完成,用的是 Input<KeyCode> 资源:
#![allow(unused)] fn main() { fn 键盘输入( input: Res<Input<KeyCode>>, ) { if input.just_pressed(KeyCOde::Space) { // 按下空格键 } if input.just_released(KeyCode::LControl) { // 释放左 Ctrl 键 } if input.pressed(KeyCode::W) { // 按下 W 键 } // 用 `.any_*` 来检测多个输入 if input.any_pressed([KeyCode::LShift, KeyCode::RShift]) { // 按住左 Shift 键或右 Shift 键 } if input.any_just_pressed([KeyCode::Delete, KeyCode::Back]) { // 按下退格键或删除键 } } }
键盘事件
要获取所有键盘活动,可以用 KeyboardInput 事件:
#![allow(unused)] fn main() { use bevy::input::keyboard::KeyboardInput; fn 键盘事件( mut event_reader: EventReader<KeyboardInput>, ) { use bevy::input::ButtonState; for event in event_reader.iter() { match event.state { ButtonState::Pressed => { info!("按下{:?}键({})", event.key_code, event.scan_code); } ButtonState::Released => { info!("释放{:?}键({})", event.key_code, event.scan_code); } } } } }
键盘事件返回键码(Key Code)和扫描码(Scan Code),扫描码是一个 u32 类型的整数 ID。
键码和扫描码
可以通过键码或扫描码来识别键盘的按键。
键码代表每个键上的符号或字母,取决于键盘布局。Bevy 用 KeyCode 枚举来表示键码。
扫描码表示键盘上的物理按键,与键盘布局无关。Bevy 对键盘扫描码的支持有限。issue:Improve keyboard input with Input
Layout-Agnostic Key Bindings
todo:不了解扫描码