Calling classes that won't loop

Hi there! I’m currently working on a game with p5 which will include some pretty complicated stuff… at least for me anyway. Hopefully you good looking people will help me to finish it in the future!

Anyway my first of many questions would be… how do I call a class without it looping in p5?

Consider my following code:

function draw() {
  lumberjack.clicked();
}

class Lumberjack {
  constructor(x, y, br, bg, bb, dr, dg, db) {
    this.x = x,
    this.y = y,
    this.br = br,
    this.bg = bg,
    this.bb = bb,
    this.dr = dr,
    this.dg = dg,
    this.db = db
  }
  body() {
    noStroke();
    fill(this.br, this.bg, this.bb);
    rect(this.x, this.y, 20, 40);
    fill(this.dr, this.dg, this.db);
    rect(this.x + 4, this.y - 2, 2, 35);
    rect(this.x + 14, this.y - 2, 2, 35);
    rect(this.x, this.y + 30, 20, 10);
    fill(91, 51, 0);
    rect(this.x, this.y + 30, 20, 2);
    fill(255);
    rect(this.x + 9, this.y + 30, 2, 2);
  }
  move() {

  }
  clicked() {
    let d = dist(mouseX, mouseY, this.x + 10, this.y + 20);
    if (d < 20) {
      console.log("I'm a lumberjack and I'm ok");
    }
  }
}

If I click on my lumberjack an infinite loop of console.logs starts.

The only way I could sort of figure out how to solve this is to put my function call in a mousePressed() function but then my console.log is still called twice.

Can I call classes without having them loop?

Thanks in advance!

Max

1 Like

Beautifier.io

Can you explain a little bit please? :slight_smile:

  • “Toggle Rects” is a sketch which contains a class called Rect.
  • Each time the canvas receives a mouse click, it iterates over all instances of Rect.
  • AFAIK, 1 click is 1 Rect color toggle.
1 Like