访问变化的变量将不起作用(Johnny-Five Joystick)
Accessing changing variables won't work (Johnny-Five Joystick)
我正在使用操纵杆开发 Arduino 游戏。我有 4 个 LED 灯,每 2 秒,其中 1 个会亮起。使用操纵杆,您必须尽快做出反应才能关闭 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
。
您需要在更改事件之外定义 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
});
我正在使用操纵杆开发 Arduino 游戏。我有 4 个 LED 灯,每 2 秒,其中 1 个会亮起。使用操纵杆,您必须尽快做出反应才能关闭 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
。
您需要在更改事件之外定义 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
});