Librerie alternative: ancora Toxiclibs.js

// height=380 lines=30
let VerletPhysics2D = toxi.physics2d.VerletPhysics2D,
    VerletParticle2D = toxi.physics2d.VerletParticle2D,
    AttractionBehavior = toxi.physics2d.behaviors.AttractionBehavior,
    GravityBehavior = toxi.physics2d.behaviors.GravityBehavior,
    Vec2D = toxi.geom.Vec2D,
    Rect = toxi.geom.Rect;

let NUM_PARTICLES = 250;

let physics;
let mouseAttractor;
let mousePos;

function setup() {
	createCanvas( 670, 380 );
    cursor(CROSS);
	// inizializzazione parametri
	physics = new VerletPhysics2D();
	physics.setDrag(0.05);
	physics.setWorldBounds( new Rect(0, 0, width, height) );
	physics.addBehavior( new GravityBehavior(new Vec2D(0, 0.15)) );
}

function addParticle() {
	let  randLoc = Vec2D.randomVector().scale(5).addSelf(width / 2, 0);
	let  p = new VerletParticle2D(randLoc);
	physics.addParticle(p);
	physics.addBehavior( new AttractionBehavior(p, 20, -1.2, 0.01) );
}

function draw() {
	background(255,0,0);
	noStroke();
	fill(255);
	if (physics.particles.length < NUM_PARTICLES) {
		addParticle();
	}
	physics.update();
	for (let i=0; i<physics.particles.length; i++) {
		let p = physics.particles[i];
		rect( p.x, p.y, 5, 5 );
	}
}

function mousePressed() {
	addParticle();
	mousePos = new Vec2D( mouseX, mouseY );
	mouseAttractor = new AttractionBehavior( mousePos, 250, 0.9 );
	physics.addBehavior( mouseAttractor );
}

function mouseDragged() {
	mousePos.set( mouseX, mouseY );
}

function mouseReleased() {
	physics.removeBehavior( mouseAttractor );
}

Il codice è riportato più che altro come esempio di conversione di sorgenti non scritti per p5.js. Il confronto può essere fatto con l'originale scritto per Processing.js.


Strutturazione dei file: