问题描述
我有一个蓝牙控制器,其中已经使用此Gamepad测试器测试了所有按钮的数量: http://html5gamepad.com/,所以我很确定按钮的值是正确的.但是,似乎没有任何反应,游戏手柄显示为已连接",只是按钮事件不起作用.下面是代码:
I have a bluetooth controller in which I've tested all the numbers of the buttons with this Gamepad tester: http://html5gamepad.com/, so I'm pretty sure the values of the buttons are correct. However, nothing seems to fire, the Gamepad is shown to be "connected", just the button events not working. Below is the code:
function gameLoop() {
if (navigator.webkitGetGamepads) {
var wgp = navigator.webkitGetGamepads()[0];
if (wgp.buttons[12] == 1 || wgp.buttons[4] == 1) {
console.log('move');
}
};
gameLoop();
我在哪里可能出错?我使用的是Chrome,因此我有webkit前缀. Gamepad测试仪会向我显示错误的按钮吗?感谢您的帮助.
Where could I have wrong? I'm using Chrome so I have the webkit prefix. Could the Gamepad tester be showing me the wrong buttons? Thanks for your help.
推荐答案
有类似的问题.在 gamepad.js/all上检查代码. js.cofee 强调指出,在每个更新周期(它们不会自动更新),我们都需要从navigator
中检索游戏手柄,请确保重复调用gameLoop()
.例如在window.setInterval(gameLoop, 100)
或window.requestAnimationFrame(gameLoop)
Had similar issue. Inspecting the code at gamepad.js/all.js.cofee highlighted that we need to retrieve gamepads from navigator
on every update cycle (they don't auto-update), make sure your gameLoop()
is called repeatedly. For example in window.setInterval(gameLoop, 100)
or 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>
)
}
}
这篇关于Gamepad API:按钮事件未触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!