web_sys::Navigator.getGamepads()
returns Result<Array, JsValue>
whereas I was hoping for an array of websys::Gamepad
objects.
How do I parse whether a gamepad button is pressed from the wasm-bindgen::JsValue
result? Is there some way to convert it to a web_sys::Gamepad
object?
Here's the setup for my attempt:
let window = web_sys::window().expect("global window does not exists");
let navigator = window.navigator();
let gamepads: Result<js_sys::Array, wasm_bindgen::JsValue> = navigator.get_gamepads();
for gp in gamepads.unwrap().iter() {
// ... how to parse Gamepad.buttons from JsValue?
}
Reference: https://rustwasm.github.io/wasm-bindgen/api/web_sys/struct.Navigator.html#method.get_gamepads
Convert JsValue into Gamepad by using wasm-bindgen::JsCast.dyn_into()
https://docs.rs/wasm-bindgen/latest/wasm_bindgen/trait.JsCast.html#method.dyn_into
let window = web_sys::window().expect("global window does not exists");
let navigator = window.navigator();
let gamepads = navigator.get_gamepads().unwrap();
for js in gamepads.iter() {
let gp: Gamepad = js.dyn_into().unwrap(); // <= convert here
let buttons = gp.buttons();
for index in 0..buttons.length() {
let js: JsValue = index.into();
console::log_2(&js, &(buttons.get(index)));
}
}