p5js-未捕获的TypeError:无法读取未定义的属性'eats'(草图:第76行)

时间:2017-11-04 09:52:59

标签: debugging p5.js

有人可以帮助我解决我在这里做错了什么。我是编程新手,目前正在大学学习p5js。我正试图创造在空间中漂浮的'细胞',当它们相互碰撞时,它们结合在一起。它工作了一分钟,但后来我收到错误

  

“未捕获的TypeError:无法读取未定义的属性'吃'(草图:第76行)”

这是我的代码:

function Cell(x, y, r) {
  this.x = x;
  this.y = y;
  this.r = r;
  this.speedx = random(-1, 1);
  this.speedy = random(-1, 1);
  this.width2 = 0.5;
  this.col = color(255);

  this.show = function() {
    fill(this.col);
    ellipse(this.x, this.y, this.r * 2);
  }

  this.move = function() {
    this.x = this.x + this.speedx;
    this.y = this.y + this.speedy;
  }

  this.bounce = function() {
    if (this.x > width || this.x < 0) {
      this.speedx = -this.speedx;
    }
    if (this.y > height || this.y < 0) {
      this.speedy = -this.speedy;
    }
  }

  // this.changeColor = function (){
  //this.col = color(random(255), random (255), random(255));
  //}

  this.eats = function(other) {
    var d = dist(this.x, this.y, other.x, other.y);
    if (d < this.r + other.r) {
      var sum = PI * this.r * this.r + PI * other.r * other.r;
      this.r = sqrt(sum / PI);
      //this.r += other.r;
      return true;
    } else {
      return false;
    }
  }

  // this.intersects = function(other){
  // var d= dist(this.x, this.y, other.x, other.y);
  //if (d < this.r + other.r) {
  //var sum = PI * this.r * this.r + PI * other.r * other.r;
  //this.r = sqrt(sum / PI);
  //this.r += other.r;
  //return true;
  //} else {
  //return false;
  //}
  //}

}

var cells = [];

function setup() {
  createCanvas(600, 600);
  for (var i = 0; i < 50; i++) {
    cells[i] = new Cell(random(width), random(height), 10);
  }
}

function draw() {
  background(0);
  for (var i = cells.length - 1; i >= 0; i--) {
    cells[i].show();
    cells[i].move();
    cells[i].bounce();

    for (var j = cells.length - 1; j >= 0; j--) {
      if (j != i && cells[i].eats(cells[j])) {
        //  cells[i].changeColor();
        // cells[j].changeColor();
        cells.splice(j, 1);
      }
    }
  }
}

1 个答案:

答案 0 :(得分:0)

您正在使用cells.splice(j, 1);从单元格数组中删除单元格。所以当它在下一个循环中检查它时,它的抛出错误。