Is this neat?
in
Programming Questions
•
1 year ago
Hi Guys,
I'm just about to sit down and write out some code to make balls act in a realistic way (i.e do not overlap and ,maybe a slight bounce/repulsion) but before I do, I was curious as to what you think of my code so far.
ie do you think it is structured okay (neat and tidy), and is it the best way of doing things (particularly my loops?).
ie do you think it is structured okay (neat and tidy), and is it the best way of doing things (particularly my loops?).
I plan on developing this a lot in the next few weeks so I'd like to make sure the basics are okay before i go on.
Thanks(in advance) for any feedback
John
CODE:
float gravity = .9;
Ball[] Balls = new Ball[1];
void setup() {
size (800, 450);
smooth();
ellipseMode(RADIUS);
background(30);
PVector posX;
for (int i = 0; i<Balls.length; i++) {
posX = new PVector(1,1);
Balls[i] = new Ball(posX, new PVector(random(10),random(10)), 20, int(random(255)), int(random(255)), int(random(255)));
}
}
void draw () {
background(30);
for (int i = 0; i<Balls.length; i++) {
DetectCollisions (i, Balls);
Balls[i].Udpate();
}
}
void mousePressed() {
// A new ball object
Ball b = new Ball(new PVector(random(10),random(10)), new PVector(random(10),random(10)), 20, int(random(255)), int(random(255)), int(random(255)));
// Append to array
Balls = (Ball[]) append(Balls,b);
}
class Ball {
PVector direction;
PVector position;
float r;
float mass;
int R, G, B;
Ball (PVector tempposition, PVector tempdirection, int radios, int tempR, int tempG, int tempB){
R=tempR;
G=tempG;
B=tempB;
r=radios;
mass = 3.14*r*r;
direction = tempdirection;
position = tempposition;
}
void Udpate(){
direction.y = direction.y + gravity;
position.x += direction.x;
position.y += direction.y;
fill (R, G, B);
ellipse (position.x, position.y, 2*r, 2*r);
// here is where the balls bounce off the four walls
if (position.x >= width - r) {direction.x *= -.9;} //right wall
if (position.x <= 0) {direction.x *= -.9;} // left wall
if (position.y > height - r) {direction.y *= -.7; // bottom
if (abs(direction.y)<1) {direction.y=0; }
position.y = height - r;
}
}
}
void DetectCollisions (int tempj, Ball[] Balls) {
int j = tempj;
for (int i = 0; i<Balls.length; i++) {
float dx = (Balls[j].direction.x) - (Balls[i].direction.x);
float dy = (Balls[j].direction.y) - (Balls[i].direction.y);
float d = sqrt(sq(dx)+sq(dy));
if(d < (Balls[i].r+Balls[j].r)){
}
}
}
1