xxxxxxxxxx
55
var myParticle;
function setup() {
createCanvas(400, 400);
myParticle = new Particle(width / 2, height / 2, 0,0);
}
function draw() {
background(200);
var dx = mouseX - myParticle.px;
var dy = mouseY - myParticle.py;
var dh2 = (dx * dx + dy * dy);
var dh = sqrt(dh2);
if (dh > 5.0) {
var attraction = 40.0;
if (mouseIsPressed){
attraction *= -1;
}
var fx = attraction * dx / dh2;
var fy = attraction * dy / dh2;
myParticle.impel(fx,fy);
}
myParticle.update();
myParticle.render();
}
//----------------------------------------
class Particle {
constructor(inpx, inpy, invx, invy) {
this.mass = 1.0;
this.FRICTION = 0.95;
this.px = inpx;
this.py = inpy;
this.vx = invx;
this.vy = invy;
}
impel(fx, fy) {
// Add an acceleration (a = F/m)
this.vx += fx / this.mass;
this.vy += fy / this.mass;
}
update() {
// Euler integration
this.vx *= this.FRICTION;
this.vy *= this.FRICTION;
this.px += this.vx;
this.py += this.vy;
}
render() {
ellipse(this.px, this.py, 40, 40);
}
}