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

问题描述 投票:1回答:3

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

如果我没有全局声明速度变量,那么女孩会进入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库,以防我使用任何时髦的功能。它有效,但我相信我可以整理一下。任何建议都会受到欢迎。

提前致谢!

javascript animation p5.js
3个回答
2
投票

你不应该在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;
  }
}

1
投票

因为speed的值在多次调用move时共享。如果你在move中声明它,那么每次调用move都会创建它,因此任何先前的speed值都将被忽略。

如果你不希望speed成为全局变量,那么你可以使它成为类Girl的属性:

class Girl {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.speed = 2;        // make 'speed' a property of the class
  }

  /* ... */

  // use 'this.speed' inside 'move' instead of just 'speed'
  move() {
    if (this.x > windowWidth + 50 || this.x < -50) {
      this.speed = this.speed * -1;
    }
    this.x = this.x + this.speed;
  }
}

0
投票

这里的问题是this.x > windowWidth + 50 || this.x < -50。尝试在this函数中记录move(),你会发现它指的是move().x而不是Girl.x。所以this.xundefined,而undefined > 10 + 50总是假的。

附:我不知道p5所以这是香草。

所以要解决这个问题,你需要声明另一个变量来获得Girl范围。

var Girl = function(){
    var self = this;
    //code goes here

   function move(){
      self.x = setValue;
      console.log(this.x) //undefined
   }
} 
© www.soinside.com 2019 - 2024. All rights reserved.