//
===========================================================================
// Name of
program: SimulBall3.pde
// Language:
Processing ver 0133
// Function:
Same as SimulBall1.pde and SimulBall2, but using OBJECTS
//
===========================================================================
//
Libraries:
// ...
// Global
variables:
// (instead
of declaring as GLOBAL variables that in fact "belong" to the
// ball
"object", we just declare a global object of class classBall!)
classBall ball;
void
setup() {
// define size of the displaying screen:
size(700,500);
//instantiate the object by calling the
constructor WITH parameters:
ball=new classBall(width/2, height/2, 0.01);
}
// The "infinite looping function":
void
draw() {
// clear the display area:
background(255);
// displays the ball
ball.displayBall();
// compute the total forces on the ball:
ball.computeForce();
// update kinematic
variables using
ball.updateNewton();
}
class classBall {
// Intrinsic variables of the ball: (as
public)
// Again, in
Processing, their default value can be set here (at declaration):
// there is no need to create a "default
setting" overloaded contructor
float x=width/2,
y=height/2; // start the ball in the middle of the screen
float x1, y1;
float vx=0, vy=0, vx0=0, vy0=0;
float ax, ay;
float fx, fy;
float m=0.01;
float dt=0.002;
float springFactor=1.0;
float ballRadius=15;
// Methods: (as public). These are just the
functions in the previsou SimulBall2.pde program,
// plus a new method, called a CONSTRUCTOR
that helps initializing the object:
// Overloaded
constructor with input parameters for initial position, mass (and perhaps
speed)
//REM1 the overloaded contructor
is MANDATORY in processing, even if it does not take any parameter
classBall(float initX, float initY, float mass) {
x=initX;
y=initY;
m=mass;
ballRadius=1000*mass; //we will make the radius is proportional to the
mass (same "density" for the balls? no! ;)
}
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;
}
}