Classe minima di un agente autonomo
Classe di un agente che si sposta casualmente a partire da un punto iniziale (partenza) e inverte la direzione quando supera i 185 pixel di distanza dal centro del canvas.
// width=300 height=300
let agente;
let centro;
function setup() {
createCanvas(300, 300);
centro = createVector(width/2, height/2);
background(200);
agente = new Agente(centro);
}
function draw() {
agente.display();
}
// DEFINIZIONE DELLA CLASSE Agente
class Agente {
constructor( partenza ) {
this.pos = partenza.copy(); // proprietà
this.vel = p5.Vector.random2D();
}
display() {
circle( this.pos.x,this.pos.y, 6 ); // visualizzazione
if (random() < 0.33) {
this.vel.rotate( random(-0.4,0.4) );
}
this.pos.add( this.vel );
if (this.pos.x < 0 || this.pos.x > width) {
this.vel.x = -this.vel.x;
}
if (this.pos.y < 0 || this.pos.y > height) {
this.vel.y = -this.vel.y;
}
}
}
class Agente {
constructor( partenza ) {
this.pos = partenza.copy(); // PROPRIETÀ
this.vel = p5.Vector.random2D();
}
display() {
circle( this.pos.x,this.pos.y, 6 ); // VISUALIZZAZIONE
if (random() < 0.33) { // AGGIORNAMENTO
this.vel.rotate( random(-0.4,0.4) );
}
this.pos.add( this.vel );
if (this.pos.x < 0 || this.pos.x > width) {
this.vel.x = -this.vel.x;
}
if (this.pos.y < 0 || this.pos.y > height) {
this.vel.y = -this.vel.y;
}
}
}
if (random() < 0.33) {
this.vel.rotate( random(-0.4,0.4) );
}
Con una probabilità del 33%, effettua una piccola rotazione casuale del vettore di spostamento.
this.pos.add( this.vel );
Applica lo spostamento.
if (this.pos.x < 0 || this.pos.x > width) {
this.vel.x = -this.vel.x;
}
if (this.pos.y < 0 || this.pos.y > height) {
this.vel.y = -this.vel.y;
}
Eventuale inversione della direzione di spostamento (vel.x = -vel.x e vel.y = -vel.y) nel caso la posizione finisca fuori dal canvas.