jeudi 21 février 2019

Why will my animation not work if I declare my variable locally?

I'm quite new to JS so please excuse my ignorance but I can't figure out why my animation if statement doesn't work if I declare my speed variable locally in the move() function.

If I don't declare the speed variable globally, the girl gets to the windowWidth and gets stuck moving a couple of pixels back and forth. Basically staying there rather than moving the other way.

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;
  }
}

I should mention I'm using the p5 library in case I'm using any funky functions. It works but I'm sure I could tidy this up a little bit. Any advice would be more than welcome.

Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire