0

My genetic 3D boids in p5js keep escaping their bounding box. I must not be doing it correctly, and could use some help. Here is a live sketch.

Here is the bounding box code:

if (this.position.x < d) {
  desired = createVector(this.maxspeed, this.velocity.y, this.maxspeed);
} else if (this.position.x > widthZone - d) {
  desired = createVector(-this.maxspeed, this.velocity.y, this.maxspeed); //-+-
}

if (this.position.y < d) {
  desired = createVector(this.velocity.x, this.maxspeed, this.maxspeed);
} else if (this.position.y > heightZone - d) {
  desired = createVector(this.velocity.x, -this.maxspeed, this.maxspeed); //+--
}

if (this.position.z < d) {
  desired = createVector(this.maxspeed, this.maxspeed, this.velocity.z);
} else if (this.position.z > depth - d) {
  desired = createVector(this.maxspeed, this.maxspeed, -this.velocity.z); //-++
}

An assist would be most appreciated.

  • Why are you using maxspeed so much when determining the new desired velocity after an object exceeds one of the boundary conditions? Can you describe the behavior you would like to see when your boids reach the edges of the bounding box? – Paul Wheeler Jul 02 '21 at 20:09
  • Just so you know, the console.log function greatly slows down your program. In your final version, you'll have to remove this. Not sure if you knew this but if you did you can ignore this comment. – user15302406 Jul 03 '21 at 15:38

1 Answers1

1

This seems like it has better results:


    if (this.position.x < d) {
      desired = createVector(this.maxspeed, this.velocity.y, this.velocity.z);
    } else if (this.position.x > widthZone - d) {
      desired = createVector(-this.maxspeed, this.velocity.y, this.velocity.z); //-+-
    }

    if (this.position.y < d) {
      desired = createVector(this.velocity.x, this.maxspeed, this.velocity.z);
    } else if (this.position.y > heightZone - d) {
      desired = createVector(this.velocity.x, -this.maxspeed, this.velocity.z); //+--
    }
    
    if (this.position.z < d) {
      desired = createVector(this.velocity.x, this.velocity.y, this.maxspeed);
    } else if (this.position.z > depth - d) {
      desired = createVector(this.velocity.x, this.velocity.y, -this.maxspeed); //-++
    }

Basically this only alters the desired velocity in the dimension(s) where the object has exceeded the boundary.

Paul Wheeler
  • 18,988
  • 3
  • 28
  • 41
  • I'm sorry I couldn't get back earlier; thank you, this nails it, and also makes complete sense-- not sure why my brain didn't just go there. It's perfect; thank you. – saito group Jul 02 '21 at 23:04
  • 1
    Welcome to Stack Overflow. It's customary to accept an answer if your problem is solved, so others know you already have an answer. It seems @Paul Wheeler solved your problem, so I would recommend accepting his answer. – user15302406 Jul 03 '21 at 15:40