有类似的问题。检查gamepad.js/all.js.cofee中的代码强调我们需要navigator
在每个更新周期检索游戏手柄(它们不会自动更新),确保您gameLoop()
的被重复调用。例如在window.setInterval(gameLoop, 100)
或window.requestAnimationFrame(gameLoop)
参考:
import * as React from 'react';
interface SampleComponentState {}
class SampleComponent extends React.Component<React.CSSProperties, SampleComponentState>{
private gamepadUpdateToken: number | null
constructor(props?: React.CSSProperties){
super(props)
}
private handleGamepad() {
const gamepads: Gamepad[] = navigator.getGamepads ?
navigator.getGamepads() :
((navigator as any).webkitGetGamepads ? (navigator as any).webkitGetGamepads() : [])
if (gamepads.length == 0){ return }
gamepads[0].buttons.forEach((button, index) => {
if (button.pressed){
console.log(`Pressed button ${index}`)
}
})
gamepads[0].axes.forEach((axe, index) => {
if (axe != 0){
console.log(`Axe ${index} moved: ${axe}`)
}
})
}
componentDidMount(){
this.gamepadUpdateToken = window.setInterval(this.handleGamepad, 100)
window.addEventListener("gamepadconnected", (event: any) => {
const newGamapad: Gamepad = event.gamepad
console.log(newGamapad)
})
}
componentWillUnmount() {
window.removeEventListener("gamepadconnected")
if (this.gamepadUpdateToken != null){
window.clearInterval(this.gamepadUpdateToken)
}
}
render(){
return (
<div>
</div>
)
}
}