Code giving me the jitters
in
Programming Questions
•
1 year ago
Anybody any suggestions as to why this is jittering so much?
My goal is to press the mouse whatever, 20, 30 40+ times to create balls, the balls should adhere to gravity, bounce off one another in a realistic way then settle in a realistic way, on top of each other. Same as if I dropped a load of balls into a container in real life. I'm semi happy with the way they adhere to gravity and semi happy with the way they bounce off one another but its just not right. they are not settling correctly.
Any suggestions???
(PS i dont intend on keeping the mouseDragged function, I will be using mouseClicked when the jitters are fixed :) )
float gravity = .9;
ArrayList balls;
void setup() {
size (800, 450);
smooth();
ellipseMode(RADIUS);
background(30);
balls = new ArrayList();
balls.add(new Ball(new PVector(random(10),random(10)), new PVector(random(10),random(10)), 20, int(random(255)), int(random(255)), int(random(255))));
}
void draw () {
background(30);
for (int i = balls.size()-1; i>= 0; i--) {
Ball b = (Ball) balls.get(i);
b.Udpate();
}
for(int i=1;i<balls.size();i++){
Ball A = (Ball) balls.get(i);
for(int j=0;j<i;j++){
Ball B = (Ball) balls.get(j);
if(!A.equals(B) && A.position.dist(B.position) < A.r + B.r){
float d, ui,uj,ki,kj;
d = dist(A.position.x,A.position.y, B.position.x, B.position.y);
ui = A.direction.x;
uj = B.direction.x;
A.direction.x = (B.mass*(uj-ui) + A.mass*ui + B.mass*uj)/( A.mass + B.mass);
B.direction.x = (A.mass*(ui-uj) + A.mass*ui + B.mass*uj)/( A.mass + B.mass);
ki = A.direction.y;
kj = B.direction.y;
A.direction.y = (B.mass*(uj-ui) + A.mass*ui + B.mass*uj)/( A.mass + B.mass);
B.direction.y = (A.mass*(ui-uj)+ A.mass*ui + B.mass*uj)/( A.mass + B.mass);
bounce(A,B);
}
}
}
}
void mouseDragged() {
balls.add(new Ball(new PVector(random(10),random(10)), new PVector(random(10),random(10)), 20, int(random(255)), int(random(255)), int(random(255))));
}
void bounce(Ball ballA, Ball ballB) {
PVector ab = new PVector();
ab.set(ballA.position);
ab.sub(ballB.position);
ab.normalize();
while(ballA.position.dist(ballB.position) < (ballA.r + ballB.r)) {
ballA.position.add(ab);
}
}
class Ball {
PVector direction = new PVector();
PVector position = new PVector();
float r;
int R, G, B;
float mass = .1;
Ball (PVector tempposition, PVector tempdirection, int radios, int tempR, int tempG, int tempB){
R=tempR;
G=tempG;
B=tempB;
r=radios;
direction = tempdirection;
position = tempposition;
}
void Udpate(){
direction.y = direction.y + gravity;
position.add(direction);
fill (R, G, B);
ellipse (position.x, position.y, r, r);
// here is where the balls bounce off the four walls
if (position.x >= width - r) { //right wall
direction.x = -.9*abs(direction.x);
}
if (position.x <= 0 + r) { // left wall
direction.x = .9*abs(direction.x);
}
if (position.y > height - r) {direction.y *= -.7; // bottom
if (abs(direction.y)<1) {direction.y=0; }
position.y = height - r;
}
}
}
1