Input
Input in raylib-rs is queried per-frame off RaylibHandle — there is no callback or
event queue. Every call snapshots the state that raylib collected during the previous
EndDrawing call. The API covers keyboard, mouse, gamepad, and touch in a uniform
style: is_*_down for level queries and is_*_pressed/is_*_released for
edge-triggered queries.
API surface
RaylibHandle::is_key_down—truewhile a key is held.RaylibHandle::is_key_pressed—trueon the first frame a key transitions to down (edge-triggered).RaylibHandle::get_mouse_position— returns aVector2in window pixels, Y-down.RaylibHandle::get_mouse_wheel_move— returns scroll delta for the current frame.RaylibHandle::is_gamepad_available— checks whether a gamepad index is connected.RaylibHandle::get_gamepad_button_pressed— returnsOption<GamepadButton>for the most recently pressed button.KeyboardKey— enum of all keyboard scancodes (e.g.,KeyboardKey::KEY_SPACE).MouseButton— left / right / middle and extended buttons.GamepadButton— cross-platform gamepad button enum.
Example
extern crate raylib;
use raylib::prelude::*;
fn main() {
let (mut rl, thread) = raylib::init()
.size(640, 480)
.title("Input demo")
.build();
while !rl.window_should_close() {
// Level query — true every frame the key is held.
if rl.is_key_down(KeyboardKey::KEY_SPACE) {
println!("SPACE held");
}
// Edge query — true only on the first frame of a press.
if rl.is_key_pressed(KeyboardKey::KEY_ENTER) {
println!("ENTER pressed");
}
let mouse = rl.get_mouse_position();
let scroll = rl.get_mouse_wheel_move();
let mut d = rl.begin_drawing(&thread);
d.clear_background(Color::RAYWHITE);
d.draw_text(
&format!("mouse: ({:.0}, {:.0}) scroll: {:.1}", mouse.x, mouse.y, scroll),
10, 10, 20, Color::DARKGRAY,
);
}
}
Gotchas
is_key_pressedis per-frame edge-triggered. It returnstrueonly on the single frame where the key transitions from up to down. If you poll it every frame and hold the key, you will see exactly onetrueunless you also checkis_key_pressed_repeatfor held-down auto-repeat.- Mouse coordinates are Y-down.
get_mouse_position().yincreases downward, which matches window pixel conventions but is the opposite of mathematical Y-up. get_gamepad_button_pressedtransmute UB (tracked-deferred). The current implementation performs atransmute::<u32, GamepadButton>on the raw integer returned by raylib. If raylib returns a value outside the knownGamepadButtonvariants, this is undefined behaviour. A soundness fix is tracked for a future PR. For now, rely only onis_gamepad_button_pressed/is_gamepad_button_downwith explicitGamepadButtonvariants.
See also
- Window and drawing — the frame loop that input is polled inside.
KeyboardKeydocs.rs — full list of key constants.
Showcase examples
Showcase examples that exercise this module: