访问变化的变量将不起作用(约翰尼五操纵杆)

时间:2019-12-16 21:47:53

标签: javascript class arduino johnny-five

我正在用操纵杆进行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 xlet y都会得到更新。

现在,我将向您展示该函数的代码。此功能每2秒重新启动一次。 问题是我需要操纵杆上的let xlet y才能使此功能正常工作, 但我不知道如何访问它们。

const playGame = () => {
  setInterval(() => {
    console.log(x, y);
  }, 2000);
};

console.log(x, y)产生undefined

1 个答案:

答案 0 :(得分:0)

您需要在更改事件的外部定义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
});