javascript - 如果我在本地声明我的变量,为什么我的动画不工作?

标签 javascript animation p5.js

我对 JS 很陌生,所以请原谅我的无知,但如果我在 move() 函数中本地声明我的速度变量,我无法弄清楚为什么我的动画 if 语句不起作用。

如果我不全局声明 speed 变量,女孩会到达 windowWidth 并卡住来回移动几个像素。基本上呆在那里而不是向另一条路移动。

let speed = 2;
class Girl {
  constructor(x, y) {
    this.x = x,
    this.y = y
  }
  body() {
    noStroke();
    fill(239, 101, 233);
    rect(this.x, this.y, 20, 40);
    fill(249, 192, 155);
    triangle(this.x, this.y, this.x + 20, this.y, this.x + 10, this.y + 15);
  }
  move() {
    if (this.x > windowWidth + 50 || this.x < -50) {
      speed = speed * -1;
    }
    this.x = this.x + speed;
  }
}

我应该提到我正在使用 p5 库,以防我使用任何时髦的函数。它有效,但我确定我可以稍微整理一下。任何建议都将非常受欢迎。

提前致谢!

最佳答案

您不应该在 move 方法中将其声明为局部变量(因为那样会在每次调用时将其重新初始化为 2),但您应该使其成为在构造函数中初始化并在 move 方法中修改的实例的属性(就像 xy)。

class Girl {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.speed = 2;
  }
  body() {
    noStroke();
    fill(239, 101, 233);
    rect(this.x, this.y, 20, 40);
    fill(249, 192, 155);
    triangle(this.x, this.y, this.x + 20, this.y, this.x + 10, this.y + 15);
  }
  move() {
    if (this.x > windowWidth + 50 || this.x < -50) {
      this.speed = this.speed * -1;
    }
    this.x = this.x + this.speed;
  }
}

关于javascript - 如果我在本地声明我的变量,为什么我的动画不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54816484/

相关文章:

Javascript 超时问题

javascript - 按需更新多个 Highcharts 实例的最佳性能

linux - 适用于 Linux 的 2D 渲染库(和视频)

javascript - 保存 Canvas 像素或状态以供以后使用的更快方法是什么?

javascript - 变量不会更改类内的属性

javascript - 测试 React Modal 组件

javascript - 哪个对象的Javascript中没有`hasOwnProperty`?

c# - WPF C# 如何为 HighlightBrush 颜色设置动画?

html - 为什么基于关键帧的动画最终会变慢?

promise - loadImage() 可以与 JavaScript Promise 一起使用吗?