p5 js“无法读取未定义的属性'show()'

时间:2017-03-13 03:57:50

标签: javascript oop object

我在这段代码中要做的就是拿出一个死粒子,然后让活着的粒子紧紧抓住并在此过程中死掉。最后,我希望有一些看起来不错的东西,这只是一个令人愉快的节目。

但我有问题......

我的代码会在运行时冻结在看似随机的点上,并说“无法读取未定义的属性'show()'。”

当它试图运行“live [i] .show();”

时,错误在第18行

有时会立即发生,有时需要一段时间,但总会发生。任何帮助表示赞赏。

提前谢谢。

var live = [];
var dead = [];

function setup() {
  createCanvas(windowWidth, windowHeight);
  background(255);
  for (var i = 0; i < 100; i++) {
    live.push(new particle(random(width), random(height), 1));
  }
  dead.push(new particle(width / 2, height / 2, 0))
}

function draw() {
  background(255);
  if (live.length > 0) {
    for (var i = 0; i < live.length; i++) {
      live[i].update(i);
      live[i].show();
    }
  }
  for (var i = 0; i < dead.length; i++) {
    dead[i].show();
  }
}

function particle(x, y, l) {
  this.x = x;
  this.y = y;
  this.l = l;
  this.speed = 5;
  this.c = 200;
  this.s = 50;
}

particle.prototype.update = function(dex) {
  this.speed *= this.l;
  this.x += random(-this.speed, this.speed)
  this.y += random(-this.speed, this.speed)
  if (this.x < 0) {
    this.x = width;
  } else if (this.x > width) {
    this.x = 0;
  }
  if (this.y < 0) {
    this.y = height;
  } else if (this.y > height) {
    this.y = 0;
  }
  for (var i = 0; i < dead.length; i++) {
    if (dist(dead[i].x, dead[i].y, this.x, this.y) < this.s && dist(dead[i].x, dead[i].y, this.x, this.y) > 0) {
      dead.push(new particle(this.x, this.y, 0));
      live.splice(dex, 1);
    }
  }
}

particle.prototype.show = function() {
  this.c *= this.l;
  strokeWeight(this.s);
  stroke(this.c);
  point(this.x, this.y);
}

1 个答案:

答案 0 :(得分:0)

如果使用map替换draw方法中的循环,它将解决您的问题。

function draw() {
  background(255);

  live.map(function(curr,i){
    curr.update(i);
    curr.show();
  })

  dead.map(function(curr){
    curr.show();
  })
}

这里是更新代码https://plnkr.co/edit/j5ueccmK4o7kbNKfeYQJ的plunkr错误是因为它试图访问大于数组最大索引的数组。

这是因为你在更新方法中使用splice改变数组并且它减少了它的长度,而具有前一长度的for循环试图将数组循环超出其长度而导致未定义。

编辑: 最好减少代码中的变异以避免这些错误。