我在做一个有操纵杆的Arduino游戏。我有4个LED灯,每隔2秒,其中一个就会亮起来。使用操纵杆,你必须尽可能快地做出反应来关闭LED灯。因此,例如,如果左侧LED亮起,您必须在操纵杆上向左转才能将其关闭。
这是我的操纵杆的代码:
var joystick = new five.Joystick({
pins: ["A0", "A1"],
});
joystick.on("change", function() {
let x = this.x;
let y = this.y
});
因此,每次操纵杆的位置发生变化时,let x
和let y
都会得到更新。
现在我将向您展示该函数的代码。此函数将每2秒重新启动一次。问题是我需要来自操纵杆的let x
和let y
来使这个函数工作,但我不知道如何访问它们。
const playGame = () => {
setInterval(() => {
console.log(x, y);
}, 2000);
};
console.log(x, y)
结果为undefined
。
发布于 2019-12-17 15:19:19
您需要在change事件之外定义x和y,才能访问它
let x, y
var joystick = new five.Joystick({
pins: ["A0", "A1"],
});
joystick.on("change", function() {
x = this.x;
y = this.y
});
const playGame = () => {
setInterval(() => {
console.log(x, y);
}, 2000);
};
这是为了修复您的示例,但是还有一种更具J5的方法(取自文档
let x, y
var joystick = new five.Joystick({
pins: ["A0", "A1"],
freq: 100 // this limit the joystick sample rate tweak to your needs
});
joystick.on("change", function() { // only fire as the sample rate freq
x = this.x;
y = this.y
});
https://stackoverflow.com/questions/59364740
复制相似问题