简体   繁体   English

访问不断变化的变量将不起作用(Johnny-Five Joystick)

[英]Accessing changing variables won't work (Johnny-Five Joystick)

I'm working on an Arduino game with a joystick.我正在使用操纵杆开发 Arduino 游戏。 I have 4 LED lights and every 2 seconds, 1 of them will light up.我有 4 个 LED 灯,每 2 秒,其中 1 个会亮起。 With the joystick, you have to react as fast as possible to turn off the LED light.使用操纵杆,您必须尽快做出反应以关闭 LED 灯。 So for example, if the left LED is lighting up, you have to go left on the joystick to turn it off.因此,例如,如果左侧 LED 亮起,您必须在操纵杆上向左移动才能将其关闭。

This is the code for my joystick:这是我的操纵杆的代码:

var joystick = new five.Joystick({
  pins: ["A0", "A1"],
 });

joystick.on("change", function() {
  let x = this.x;
  let y = this.y
 });

So every time that the position of the joystick changes, let x and let y will get an update.所以每次操纵杆的位置改变时, let xlet y都会得到更新。

Now I will show you the code of the function.现在我将向您展示该函数的代码。 This function will restart every 2 seconds.此功能将每 2 秒重新启动一次。 The problem is that I need the let x and let y from the joystick to make this function work, but I don't know how to access them.问题是我需要操纵杆上的let xlet y来使这个函数工作,但我不知道如何访问它们。

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

The console.log(x, y) results in undefined . console.log(x, y)结果是undefined

you need to define x and y OUTSIDE of change event so you can access it您需要在更改事件之外定义 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);
};

this is to fix your example, but there is an even more J5 way (taken from the docs这是为了修复您的示例,但还有更多 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
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM