Skip to content

Instantly share code, notes, and snippets.

Created November 16, 2013 11:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/7499236 to your computer and use it in GitHub Desktop.
Save anonymous/7499236 to your computer and use it in GitHub Desktop.
ArrayList<Ball> balls;
int ballWidth = 48;
void setup() {
size(600, 600);
balls = new ArrayList<Ball>();
balls.add(new Ball(width/2, 0, ballWidth)); // Start by adding one element
}
void draw() {
background(255);
for (int i = balls.size()-1; i >= 0; i--) {
Ball ball = balls.get(i);
ball.move();
ball.display();
if (ball.finished()) {
// Items can be deleted with remove().
balls.remove(i);
}
}
}
void mousePressed() {
// A new ball object is added to the ArrayList, by default to the end.
balls.add(new Ball(mouseX, mouseY, ballWidth));
}
////////////////////////////////////////////////////////////////
// Ball class
class Ball { // Define the ball class
// Attributes
float x, y; // the x and y location
float radius; // its radius in pixels
float speed = 5.0; // The speed at which the ball is moving
float gravity = 0.1; // the rate of increase of speed
float dx = 1; // amount of lateral movement
float dampen = -0.9; // amount of dampening after each bounce
// Constructors
// Default Constructor
Ball(float x, float y, float r) {
// set up ball with position (x, y)
this.x = x;
this.y = y;
// size, r pixels
radius = r;
} // ball()
// Behaviors
void display() {
// display the ball
// set color attributes
noStroke();
fill(0,255,0);
// draw the ball
ellipse(x, y, 2*radius, 2*radius);
} // display()
void move() {
x = x + dx;
y = y + speed;
speed = speed + gravity;
// check to see if it bounces
bounce();
} //move()
void bounce() {
if (x > (width-radius)) { // bounce against the right edge
x = width-radius;
dx = -dx;
}
if (x < radius) { // bounce against the left edge
x = radius;
dx = -dx;
}
if (y > (height-radius)) { // bounce against the bottom edge
y = height-radius;
speed = speed * dampen ;
}
} // bounce()
boolean finished() {
if(abs(speed) <= 0.3) {
return true;
}
return false;
}
} // class ball
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment