Ball in gravity and air drag (processing)
by oscar6echo
HTML
<canvas width="600px" height="700px"></canvas>
CSS
canvas {
display:block;
margin:20px;
border:1px solid #666;
}
</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 prevents javascript in body from throwing error
</script>
<style>
JavaScript
// size
int height = 700;
int width = 600;
// time
int nbFramePerSec = 80;
float drawPeriod = 1/nbFramePerSec;
// ground variables -------------------------------------------
int nbSegment = 40;
Ground[] ground = new Ground[nbSegment];
float[] groundHeight = new float[nbSegment + 1];
//physics variables
float mass = 0.1; // kg
float radius = 15; // 1px = 1cm <<--------
float bounceFactor = -0.95; // dimensionless
float Cd = 0.47; // drag coef, dimensionless
float rho = 1.22; // density, kg / m^3
float ag = 9.81; // acceleration, m/s^2
float Fx, Fy, ax, ay;
// build ball -------------------------------------------
// top left corner is (x, y) = (0, 0)
// bottom right corner is (width, height) = (0, 0)
// x (cm), y (cm), vx (cm/s), vy (cm/s)
int xinit = round(width * 0.0);
int yinit = round(width * 0.95);
int vxinit = 8; // cm/s
int vyinit = -18; // cm/s
Ball ball = new Ball(xinit, yinit, vxinit, vyinit, radius, mass, bounceFactor);
float A = PI * (ball.r/100) * (ball.r/100); // surface, m^2
// setup(), executed once at inception -----------------------------------
void setup() {
size(width, height);
background(255);
smooth();
frameRate(nbFramePerSec); // frames per sec
// calculate ground height for each nbSegment+1 points
for (int i = 0; i < groundHeight.length; i++) {
groundHeight[i] = random(height - 45, height - 30);
}
// build ground over width of canvas, regardless of segment number
float nbSegmentFloat = nbSegment;
for (int i = 0; i < nbSegment; i++) {
ground[i] = new Ground(i*width/nbSegmentFloat, groundHeight[i], (i+1)*width/nbSegmentFloat, groundHeight[i + 1]);
}
}
void draw() {
// display white background with opacity
noStroke();
fill(255, 999); // first arg is white=255, second arg is opacity 999=opaque and 0=transparent
rect(0, 0, width, height);
// draw ground
fill(153);
beginShape();
for (int i = 0; i < nbSegment; i++) {
vertex(ground[i].x1, ground[i].y1);
}
...