Implementazione delle regole con una classe

Se sono necessarie più istanze dello stesso oggetto è utile definire e usare una classe:

// height100 lines=auto
function Cerchio() {
    this.pos = createVector();     // PROPRIETÀ
    this.vel = createVector( 1.7, 1.9 );
    this.display = function() {    // VISUALIZZAZIONE
        ellipse( this.pos.x, this.pos.y, 6, 6 );
    };
    this.update = function() {     // AGGIORNAMENTI
        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;
        }
    };
}

var cerchio;

function setup() {
    cerchio = new Cerchio();
}

function draw() {
    background(220);
    cerchio.display();
    cerchio.update();
}

 

Quando i codici non sono particolarmente complessi, le operazioni di aggiornamento vengono spesso inserite nel metodo display() (o render() o anche draw()).