Processing 2.9 Gravitational Attraction

Nature of code, Gravity force, attraction. p.90 2015-08-01

by schrodingers

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/processing.js/1.4.13/processing.min.js"></script>
<canvas></canvas>

CSS

</style> <script type="text/javascript"> window.addEventListener('load', function() {
    var scripts=document.body.getElementsByTagName('script');
    var canvases=document.body.getElementsByTagName('canvas');
    new Processing(canvases[0], scripts[0].text);
}
, false);
 // Here prevent javascript in body from throwing error </script> <style>

JavaScript

/* 
 title: 2.9 Gravitational Attraction, p.90, example 2.6
 date: 2015-08-01
 */
Mover[] movers = new Mover[10];
Attractor a;
color violet = color(58, 48, 66);
color yellow = color(237, 230, 35);
color cyan = color(5, 190, 255);

void setup() {
    size(800, 600);
    smooth(6);
    for (int i = 0; i < movers.length; i++) {
        movers[i] = new Mover(random(0.1, 1.5), random(width), random(height));
    }
    a = new Attractor();
}

void draw() {
    fill(violet, 10);
    rect(0, 0, width, height);
    a.display();
    for (int i = 0; i < movers.length; i++) {
        PVector force = a.attract(movers[i]); // apply attraction force from Attractor on Mover
        movers[i].applyForce(force);

        movers[i].update();
        movers[i].display();
    }
}


class Attractor {
    float mass;
    PVector location;
    float G;

    Attractor() {
        location = new PVector(width / 2, height / 2);
        mass = 20;
        G = 1;
    }
    PVector attract(Mover m) {
        PVector force = PVector.sub(location, m.location);
        float distance = force.mag();
        distance = constrain(distance, 5.0, 25.0);

        force.normalize();

        float strength = (G * mass * m.mass) / (distance * distance);
        force.mult(strength);
        return force;
    }

    void display() {
        noStroke();
        ellipseMode(CENTER);
        fill(yellow, 10);
        ellipse(location.x, location.y, mass * 2, mass * 2);
    }
}


class Mover {
    PVector location;
    PVector velocity;
    PVector acceleration;
    float mass;

    Mover(float m, float x, float y) {
        mass = m;
        this.location = new PVector(x, y);
        this.velocity = new PVector(1, 0);
        this.acceleration = new PVector(0, 0);
    }


    // Newton’s second law.
    void applyForce(PVector force) {
        //Receive a force, divide by mass, and add to acceleration.
        PVector f = PVector.div(force, mass);
        acceleration.add(f);
    }

    void update() {
    ...