Back

Technologies:

javascriptjavascript
avatar
Tolerim
a minute ago

How can I construct a branching structure in p5js by utilizing WEBGL and classes?

I have created a p5js sketch that features two classes to simulate the growth of a plant, similar to a tree. However, I am facing difficulties implementing branch growth from the main structure. I was able to spawn branches, but they seem to only grow from the root of the plant. You can view the original version here, and the current version with the branch spawn logic here. Additionally, I have included the code snippet below for your reference. Please enclose the code in
 tags to utilize it.
Answers(1)
avatar
Tolerim
a minute ago
Verified Answer
It seems like you are trying to add branches to your p5js sketch using classes. I see that you have already created a CoralBranch class, but it doesn't seem to be working as expected. From looking at your code, it seems like you are trying to spawn branches when the length of your segments array reaches a certain value. However, your segments array is being updated every time the grow() function is called, so branches will spawn at every iteration of the for loop that checks the condition. To fix this, you can add a variable to keep track of whether a branch has been spawned at the current segment, and only spawn a branch if that variable is false. Here's an example of how you can do this:
class CoralGrowth {
  constructor(x, y, z) {
    // ...
    this.branchSpawned = false; // new variable to keep track of branch spawning
  }

  grow() {
    // ...

    if (
      !this.branchSpawned && // only spawn branch if it hasn't been spawned yet
      this.segments.length >= this.maxSegments * this.branchSpawnThreshold &&
      this.segments.length % this.branchLength == 0
    ) {
      for (let i = 0; i < 2; i++) {
        // spawn multiple branches at once
        let branch = new CoralBranch(
          nextSegment.x,
          nextSegment.y,
          nextSegment.z,
          this.branchAngle * random(-0.5, 0.5)
        );
        // ...
        this.branches.push(branch);
      }
      this.branchSpawned = true; // set flag to true
    }

    // ...

    for (let i = 0; i < this.branches.length; i++) {
      this.branches[i].grow();
    }

    // ...

    if (this.branchSpawned) { // reset flag when new segment is generated
      this.branchSpawned = false;
    }
  }
}
This should ensure that branches are only spawned once per branchLength segments. Let me know if this helps!
;