Scurrying Ants – Week 9

Inspiration

For my inspiration this week, I wanted to replicate the ants that always scurry around with each other and sometimes if they find food or something they want, they tend to move in a herd.

I first had the images on the background to represent dirt in some way and to have the ant image.

After the graphics aspect was done, I wanted to implement the actual motion and have the ants be represented as circles for now. I needed to work on two particular functions, separate and align.

For the separate function, I needed to create a vector and have the separation movement be coded within that vector.

separate(ants) {
    let steer = createVector();
    let count = 0;
    for (let other of ants) {
      let d = dist(
        this.pos.x,
        this.pos.y,
        other.pos.x,
        other.pos.y
      );
      if (other != this && d < this.desiredSeparation) //make sure the ant is not comparing with isteld and within certain distance
      {
        let diff = p5.Vector.sub(this.pos, other.pos);
        diff.normalize();
        diff.div(d);
        steer.add(diff);
        count++;
      }
    }
    if (count > 0) {
      steer.div(count);
    }
    if (steer.mag() > 0) {
      steer.setMag(this.maxSpeed);
      steer.sub(this.vel);
      steer.limit(this.maxForce);
    }
    return steer;
  }

For the align function, it is the same structure as the separate function ,but we use addition instead of subtraction.

align(ants) {
    let sum = createVector();
    let count = 0;
    let perceptionRadius = 50;

    for (let other of ants) {
      let d = dist(
        this.pos.x,
        this.pos.y,
        other.pos.x,
        other.pos.y
      );

      if (other !== this && d < perceptionRadius) {
        sum.add(other.vel);
        count++;
      }
    }

    if (count > 0) {
      sum.div(count);
      sum.setMag(this.maxSpeed);
      let steer = p5.Vector.sub(sum, this.vel);
      steer.limit(this.maxForce);
      return steer;
    } else {
      return createVector();
    }
  }

This was the output with circles and I wanted the head of my ant to always point the way in the direction it was going.

display() {
   push();
   translate(this.pos.x, this.pos.y);
   rotate(this.vel.heading());
   image(this.img, 0, 0, 15, 15);
   pop();
   // circle(this.pos.x, this.pos.y, 10);
 }

This is my final output and I would want to add more interactivity next time by making the user have something ‘sweet’ as the mouse movement, so the ants move towards the mouse.

Leave a Reply

Your email address will not be published. Required fields are marked *