p5.js creating a class for the first time.

Hi,

I am trying to create a class of circles in p5.js and draw them. It is fairly simple. I am trying to adapt a piece of code from processing to p5.js and my 'for in' statement does not work and I get an error ' Uncaught SyntaxError: Unexpected identifier '

I don't understand completely why this is not working and what I should change in this code.

Any help regarding creating a class in p5.js would be much appreciated.

Thanks,

Omer

var canvasOfset = 10;
var circles;



function setup() {
  circles = new Array();
  createCircles();
  createCanvas(windowWidth - canvasOfset, windowHeight - canvasOfset);
  frameRate(30);
  background(0);
}


function createCircles() {
  for (var i = 0; i < windowWidth; i++) {
    if (i % 100 == 0) {
      circles.push(new Circle(i, i, 100))
    }
  }
}


function draw() {
  background(0, 5);

  for (Circle c in circles) {
    ellipse(c.x, c.y, c.scale);
    fill(255, 0, 0);
    noStroke();
  }
}

class Circle {

  constructor(x, y, scale) {
    this.x = x;
    this.y = y;
    this.scale = scale;
  }
}


function windowResized() {
  resizeCanvas(windowWidth - canvasOfset, windowHeight - canvasOfset);
}

Answers

  • Sorry, I believe it should be

    for (Circle c : circles) {

    not

      for (Circle c in circles) {
    
  • Answer ✓

    @omerpekin - p5js is JavaScript; so isn't a typed language... So you don't define the c variable in your loop as a Circle; but just use a general variable declaration like var; or these days const or let:

    BUT - for...in is NOT a good choice of loop to use on Objects in JS (see this); which leads to @GoToLoop's suggestion: for...of is the safer option to iterate over Objects ;)

    `for (let c of circles) {`
    
  • Hi,

    Thank you very much for your answers. Finally, I managed it the simpler way ( I guess) or at least the way I understand. This is how my code looks like:

    for (var i = 0; i < circles.length; i++) {}

Sign In or Register to comment.