Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

76
Views
Trying to add separation to boids simulation in p5js. Collision teleporting boids to origin

I'm trying to make a boids simulation in p5js. Currently I'm trying to implement the separation rule, following this tutorial. (The relevant section is 6.11). Whenever two boids collide, one of them gets "teleported" to the origin instead of avoiding the other boid. I've narrowed down the problem to the separate function in my Boid class, which is below.

separate(boids) {
    var count = 0
    var desiredVelocity = createVector(0, 0)
    // loop through boids to find if any are too close
    for (const boid of boids) {
      const distance = this.position.dist(boid.position)
      if ((distance < this.desiredSeparation) && (boid.id != this.id)) {
        count += 1
        // too close; move away from boid
        var steerAwayVector = boid.position.sub(this.position)
        this.drawArrow(steerAwayVector, this.position, '#eb9ac1')
        steerAwayVector.normalize()
        steerAwayVector.div(distance)
        desiredVelocity.add(steerAwayVector)
      }
    }
    if (count > 0) {
      desiredVelocity.setMag(this.maxSpeed)
      var steer = desiredVelocity.sub(this.velocity)
      steer.limit(this.maxForce)
      this.applyForce(steer)
    }
  }

See my full code on github here. What/where is the problem? How do I fix this behavior?

7 months ago ยท Juan Pablo Isaza
Answer question
Find remote jobs