有類似的問題。檢查代碼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>
)
}
}