//
===========================================================================
// Name of
program: SimulBall2.pde
// Language:
Processing ver 0133
// Function:
Simulation of a 2D bouncing ball "attached" to the mouse cursor.
// Same as SimulBall1.pde, but using
functions.
// through a
spring-like force.
//
===========================================================================
// Author:
Alvaro Cassinelli
//
===========================================================================
// Versions:
//
[14.11.2007] - the initial program
//
Libraries:
// ...
// Global
variables (here, the intrinsic variables of the ball among
// other
things).
//
================================================================
float x,
y, x1, y1;
float vx, vy, vx0, vy0;
float ax,
ay;
float fx, fy;
float m;
float dt;
float springFactor=100.0;
float ballRadius=10;
void
setup() {
// define size of the displaying screen:
size(700,500);
// initialize variables (in processing, this
can be done during declaration)
x=width/2;
y=height/2; // start in the middle of the
screen
vx=0;
vy=0;
vx0=0;
vy0=0;
m=0.01;
dt
=0.002; // in “virtual” seconds (one loop takes dt).
springFactor=1.0;
ballRadius=15;
}
// The "infinite looping function":
void
draw() {
// clear the display area:
background(255);
// displays the ball
displayBall();
// compute the total forces on the ball:
computeForce();
// update kinematic
variables using
updateNewton();
}
void displayBall() {
// display the ball as a solid disc:
fill(0,0,250);
ellipse(x, y, ballRadius, ballRadius);
}
void computeForce() {
// compute fx and fy from input device
(or anything else).
// Compute force from mouse position:
fx
= springFactor*(mouseX -
x);
fy
= springFactor*(mouseY -
y);
}
void updateNewton() {
// update motion variables using
// compute current acceleration:
ax=fx/m;
ay=fy/m;
// update position :
x1=x+vx*dt+ax*dt*dt/2;
y1=y+vy*dt+ay*dt*dt/2;
//update speed :
vx=vx0+ax*dt;
vy=vy0+ay*dt;
// Test boundary conditions:
if
((x1<0)||(x1>width)) {
vx=-0.98*vx0;
x1=x;
};
if
((y1<0)||(y1>height)) {
vy=-0.98*vy0;
y1=y;
};
// Update the current position and past
speed:
x=x1; y=y1;
vx0=vx; vy0=vy;
}