3

I am trying to create an array of vertices, and then run the 'rect' function over this array to display an arbitrary amount of rectangles. Right now, I have:

var vertices = new Array();

function setup() {
    createCanvas(600, 600);
    ...
    iter(width/2 - c/2, height/2 - c/2, c);
    var i;
    for (i = 0; i < vertices.length; i++) {
        fill(200);
        rect(vertices[i]);
    }
}

And then:

function iter(x, y, len) {
    r_1 = random(0, 1);

    if (r_1 < 0.5){
        vertices.push(x, y - len*0.5, len*0.5, len*0.5);
    }
}

I have seen lots about using map or foreach to run functions over arrays but I don't know why this doesn't work (specifically, using a for loop to run a function over an array). I am obviously very new to all this stuff! An explanation of what I seem to misunderstand would be very much appreciated.

Thanks

2
  • 4
    What exactly is your expected output? Commented Dec 15, 2018 at 22:29
  • A canvas displaying rectangles described by the data inside the array 'vertices' Commented Dec 15, 2018 at 22:30

1 Answer 1

1

When you do

vertices.push(x,y-len*0.5,len*0.5,len*0.5)

you're calling push with four arguments, so four items get pushed to the array. Because you're calling rect with verticies[i] later, it sounds like each item of verticies should be a data container of some sort - an array or an object, otherwise the points of each vertex will be separated out over multiple indicies. For example, if you were to use an array:

function iter(x, y, len) {
  r_1 = random(0, 1);
  if (r_1 < 0.5){
    vertices.push([x, y - len*0.5, len*0.5, len*0.5]);
  }
}

And then spread each array in the vertex array into the rect argument list:

function setup() {
  createCanvas(600, 600);
  // ...
  iter(width/2 - c/2, height/2 - c/2, c);
  var i;
  for (i = 0; i < vertices.length; i++) {
    fill(200);
    rect(...vertices[i]);
  }
}

This assumes that rect is a function that accepts 4 arguments. (you could also change rect so that it accepts a single array as an argument instead, and avoid the spread syntax, if you wanted)

You also might consider using an array literal rather than new Array - calling the Array constructor is rarely a good idea:

var vertices = [];
Sign up to request clarification or add additional context in comments.

1 Comment

I should have seen that. Thanks so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.