Create forces. Friction. ex. 2.4
p.82 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.82 Create forces. Example 2.4
date: 2015-07-25
*/
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, 3), 0, 0);
}
}
void draw() {
background(200);
// colorMode(HSB, 360, 100, 100);
PVector wind = new PVector(0.01, 0);
// float m = movers[i].mass;
PVector gravity = new PVector(0, 0.1);
for (int i = 0; i < movers.length; i++) {
float c = 0.01; // coefficient of friction
PVector friction = movers[i].velocity.get();
friction.mult(-1);
friction.normalize();
friction.mult(c);
movers[i].applyForce(friction);
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 *=...