Create forces. ex.2.2

Nature of code.

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: p.77 Create forces. Example 2.1, 2.2
 date: 2015-07-24
 */
Mover m1 = new Mover(10, 0, height / 2);
Mover m2 = new Mover(0.1, width, height / 2);
Mover[] movers = new Mover[10];


void setup() {
    size(600, 600);
    smooth(8);
    noStroke();
    background(200);
    for (int i = 0; i < movers.length; i++) {
        movers[i] = new Mover(random(0.1, 5), 0, 0);
    }
}

void draw() {
    background(200);
    //  colorMode(HSB, 360, 100, 100);

    for (int i = 0; i < movers.length; i++) {
        PVector wind = new PVector(0.01, 0);
        float m = movers[i].mass;
        PVector gravity = new PVector(0, 0.1 * m);
        movers[i].applyForce(wind);
        movers[i].applyForce(gravity);
        movers[i].update();
        movers[i].display();
        movers[i].checkEdges();

    }
}


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

    Mover(float _m, float _x, float _y) {
        mass = _m;
        location = new PVector(_x, _y);
        velocity = new PVector(0, 0);
        acceleration = new PVector(0, 0);
    }

    void applyForce(PVector force) {
        PVector f = PVector.div(force, mass);
        acceleration.add(f);
    }


    void update() {
        velocity.add(acceleration);
        location.add(velocity);
        acceleration.mult(0);
    }

    void display() {
        fill(115);
        ellipse(location.x, location.y, mass * 20, mass * 20); // size depends of mass
    }

    void checkEdges() {
        if (location.x > width) {
            location.x = width;
            velocity.x *= -1;
        } else if (location.x < 0) {
            velocity.x *= -1;
            location.x = 0;
        }
        if (location.y > height) {
            velocity.y *= -1;
            location.y = height;
        } else if (location.y < 0) {
            velocity.y *= -1;
            location.y = 0;
        }
    }
}