在画布JS P5上循环对象

萨利姆·安图恩

这是我的第一个问题!我使用JS P5,我创建了一个创建椭圆的函数。我想在整个画布上以每个椭圆之间一定的距离循环此椭圆。

我没有使用普通的椭圆,因为我想稍后再在每个椭圆上放置另一个函数。所以我的问题是如何在我创建的对象上应用for循环和嵌套循环。

这是我的代码,我在这里有随机的方式,但是我想要的是像整个网格上的网格一样的出色。

像这个例子

let shapes = [];

function setup() {
  createCanvas(600, 600);
  for (let i = 0; i < 500; i++){
    let x = random(width);
    let y = random(height);

    shapes[i] = new shape(x,y,20);
  }
}

function draw() {
  background(220);

  for (let i = 0; i < shapes.length; i++){
    shapes[i].display();
  }
}


function shape(tx, ty, ts) {
  this.x = tx;
  this.y = ty;
  this.size = ts;
  this.angle = 0;

  this.update = function(mx, my) {
    this.angle = atan2(my - this.y, mx - this.x);
  };

  this.display = function() {
    push();
    fill(153, 204, 0);
    ellipse(this.x, this.y, this.size, this.size);
    pop();
  };
}

哈克勒

编辑答案:

let shapes = [];

function setup() {
    createCanvas(600, 600);
    for(var x=0;x<width;x+=30){
        for(var y=0;y<height;y+=30){
            shapes.push(new shape(x,y,20));
        }
    }
}

function draw() {
    background(220);

    for (let i = 0; i < shapes.length; i++){
        shapes[i].display();
    }
}


function shape(tx, ty, ts) {
    this.x = tx;
    this.y = ty;
    this.size = ts;
    this.angle = 0;

    this.update = function(mx, my) {
        this.angle = atan2(my - this.y, mx - this.x);
    };

    this.display = function() {
        push();
        fill(153, 204, 0);
        ellipse(this.x, this.y, this.size, this.size);
        pop();
    };
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章