如何使对象使用其自身的数据进行空间引用?

时间:2019-02-21 23:11:40

标签: javascript class object animation

如何使对象使用其自身的空间数据,而不必指定其在画布中的位置?

例如,每当我需要为if语句指定边界或一定数量的像素时,我就必须找到该对象在画布上的位置,并告诉if语句我要在表达式上的哪个位置执行

我想对对象说“好的,现在就去,将x像素向右移动”。

例如,在这里看看我的课程:

function setup() {
  createCanvas(windowWidth, windowHeight);
  trees = new Trees(200, 200);
}

class Trees {
  constructor(x, y) {
    this.x = x,
    this.y = y,
    this.a = 0
  }
  trunk() {
    noStroke();
    fill(126, 60, 1);
    rect(this.x + 3, this.y, 14, 40);
    triangle(this.x + 10, this.y + 30, this.x - 4, this.y + 40, this.x + 24, this.y + 40);
  }
  leaves() {
    fill(71, 215, 45);
    ellipse(this.x + 3, this.y - 5, 25);
    ellipse(this.x + 10, this.y - 15, 25);
    ellipse(this.x + 17, this.y - 5, 25);
  }
  shudder() {
    if (mouseIsPressed) {
      this.a = 4;
      if (this.x < this.x - 2 || this.x > this.x + 2) { // this won't work
        this.a = this.a * -1;
      }
    } else {
      this.a = 0;
    }
    this.x = this.x + this.a;
  }
}

您可以在这里看到我要做什么。

我已经通过引用画布成功地将对象移动了,但是必须有一种方法可以简单地引用对象所在的位置,然后将其偏移几个像素?

我不想这样做:

function setup() {
  createCanvas(windowWidth, windowHeight);
  trees = new Trees(200, 200, 198, 202); // not what I want
}

class Trees {
  constructor(x, y, l, r) {
    this.x = x,
    this.y = y,
    this.l = l,
    this.r = r,
    this.a = 0
  }
  trunk() {
    noStroke();
    fill(126, 60, 1);
    rect(this.x + 3, this.y, 14, 40);
    triangle(this.x + 10, this.y + 30, this.x - 4, this.y + 40, this.x + 24, this.y + 40);
  }
  leaves() {
    fill(71, 215, 45);
    ellipse(this.x + 3, this.y - 5, 25);
    ellipse(this.x + 10, this.y - 15, 25);
    ellipse(this.x + 17, this.y - 5, 25);
  }
  shudder() {
    if (mouseIsPressed) {
      this.a = 4;
      if (this.x < this.l || this.x > this.r) {
        this.a = this.a * -1;
      }
    } else {
      this.a = 0;
    }
    this.x = this.x + this.a;
  }
}

有没有办法实现我的要求?

谢谢!

0 个答案:

没有答案