OOP: Object generated via a for loop
in
Programming Questions
•
1 year ago
Hi guys !
Newbie here. I've been learning processing since 1 month now, with Dan's amazing book. Processing in really awsome !!
I'm trying to write a sketch where several balls fall and bounce for an exercise. It worked, and then I decided to ad some randomness to the whole thing (speed, radius of balls, distance between balls).
If I implement the balls proprieties randomness in the for loop, the parameters change with every frame as the loop is in the draw function. So I had to use OOP. No problems defining the object itself. But to call it, I had so mess with arrays (I got the idea in this thread:
http://processing.org/discourse/beta/num_1250442400.html. But the sketch doesn't work. I've been looking at it for 2 days, and still can't find the problem. Mind giving me a hand on this one ?
Heres my sketch.
- float gap=random(10, 30);
- //calling the object
- Ball[] myBalls = Ball[10];
- void setup () {
- size(500, 500);
- smooth();
- //println(gap);
- // Heres the tricky part.
- for (int i=0, j=0; i<width; i+=gap, j++){
- myBalls[j] = new Ball(i, 20);
- }
- }
- void draw () {
- background (0);
- for (int i=0; i<myBalls.lenght; i++){
- myBall[i].drop();
- myBall[i].display();
- }
- //new tab
- class Ball {
- float x;
- float y;
- float r;
- float v;
- float g;
- Ball(float tempx, float tempy) {
- x = tempx;
- y = tempy;
- g=.9;
- v=5 + random (-2, 2);
- r=random (15, 25);
- }
- void display(){
- ellipseMode(CENTER);
- fill(255);
- ellipse (x, y, r, r);
- println("speed : "+v);
- println("radius: "+r);
- }
- //Heres the code of gravity
- void drop(){
- y=y+v;
- v=v+g;
- if (y>height) {
- v*=-0.9;
- }
- }
- }
Paul
1