The above sketch draws a single agent that moves within the boundary of the sketch. In this example, I am using a class to create the agent. Using classes is considered object-based programming. A class creates custom attributes and behaviors specific to that object. In this case, we are only creating one agent, but classes are ideal for creating multiple instances of similar objects. You can find this example here and an explanation of the code below:
var agent;
function setup() {
createCanvas(600, 600);
agent = new addAgent(random(20,width-20),random(20,height-20),10);
}
First I declare a variable for the agent. This will hold the object we create with the class. In setup I set the size of the canvas and I add an agent by assigning a new agent object to the agent variable. The parameters for the agent are x position, y position, and radius.
function draw() {
background(220);
agent.run();
}
The draw function is pretty simple right now. The only thing I call besides the background is a function in my agent object called run. Run will call any functions within the object. These functions include drawing the circle and calculating the agent’s next position but can include many more.
class addAgent{
constructor(x,y,r) {
this.x = x;
this.y = y;
this.rad = r;
this.speedx = random(-1,1);
this.speedy = random(-1,1);
}
Here is where I begin the class. It is like a function but instead of adding parameters in the call there is an internal function called “constructor.” This is where you assign the variables in the call “addAgent.” It is also where you set initial values which will only be set once, in this case, speed for x and y. All variables are relative to this function and should be preceded by “this.” Everything below is within the class.
run(){
this.move();
this.show();
}
Here is the run function we call in draw for the agent. This function simply call the functions move() and show().
move(){
this.x = this.x + this.speedx;
this.y = this.y + this.speedy;
if((this.x > width-10) || (this.x < 10)){
this.speedx = this.speedx * -1;
}
if((this.y > height-10) || (this.y < 10)){
this.speedy = this.speedy * -1;
}
}
Here is the move function it simply calculates the new x and y positions by adding the x and y speed to the current values. It also tests to see if the new x or y positions are greater than the boundary of the sketch, in that cases it reverses the speed in that coordinate.
show(){
fill(0);
circle(this.x,this.y,this.rad);
}
}
The show() function simply draws a circle at the objects current position. Then we close out the class.