1.3 Agents with Distance Threshold

In this example, I have added an additional function to the class from the example in 1.2 Multiple Agents. I added a function called checklist() that checks the distance between an agent and all f the other agents. If the agent is within a certain distance to another agent it turns red. I added a slider to adjust this distance threshold. Below is an explanation of the changes and you can find this example here.

   run(){
    this.checkdist();
    this.move();
    this.show();
  }

I added an additional function called checklist() to the class and I need to call that from the run function.

 constructor(x,y,r) {
    this.x = x;
    this.y = y;
    this.rad = r;
    this.speedx = random(-1,1);
    this.speedy = random(-1,1);
    this.safe = true;
  }

I added one variable to the contractor in the class. The variable “safe” is a boolean and will toggle back and forth depending on if an agent is within the distance threshold of another agent. If safe = true then the agent is safe or black and if it is false then the agent is red.

 
  show(){
    noStroke();
    if(this.safe == true){
      fill(0);
    }else{
      fill(255,0,0);
    }
    circle(this.x,this.y,this.rad);
    noFill();
    stroke(200);
    circle(this.x,this.y,distthreshold*2);
  }

I added a bit more functionality to the show() function that I am checking to see if safe is true or false to set the fill color for the agent. I am also drawing a light circle that shows the distance threshold around the agent. It is multiplied by 2 because it is a radius.

  checkdist(){
    var checkcount = 0;
    for(var i = 0; i < agents.length; i++){
      var dcheck = dist(this.x,this.y,agents[i].x,agents[i].y)
      if(dcheck < distthreshold){ checkcount ++; } } if(checkcount > 1){
      this.safe = false;
    }else{
      this.safe = true;
    }
  }

This is the new checklist function() I have added at the end of the class. It contains a look that checks the distance between the agent and the other agents in the sketch. This will run for each agent. I use a variable called “checkcount” because the conditional in the loop will always be true at least once when the loop cycles through the current agent it will measure its distance compared to itself which will be 0. “checkcount” needs to be greater than one or at least 2 for the agent to be considered to close to another and for safe to equal false.