Skip to content

Instantly share code, notes, and snippets.

@raheelahmad
Created October 12, 2011 17:51
Show Gist options
  • Save raheelahmad/1281971 to your computer and use it in GitHub Desktop.
Save raheelahmad/1281971 to your computer and use it in GitHub Desktop.
Mouse Inside Ball Objects
class MovingBall {
float x, y, w, maxW, speed; // variables for drawing the ellipse
boolean movingForward;
boolean movingUp;
boolean expanding;
boolean mouseInside;
float r, g, b;
void drawItself() {
if (mouseInside)
fill(random(0, 255), random(0, 255), random(0, 255));
else
fill(r, g, b);
ellipse(x, y, w, w);
}
void update() {
//if (expanding)
// w += 1;
//else
// w -= 1;
if (movingForward)
x += speed;
else
x -= speed;
if (movingUp)
y -= speed;
else
y += speed;
}
void check() {
if (w <= 0)
expanding = true;
if (w >= maxW)
expanding = false;
if (y <= 0)
movingUp = false;
if (y >= height)
movingUp = true;
if (x >= width)
movingForward = false;
if (x <= 0)
movingForward = true;
}
}
MovingBall[] balls; // declaration
int numBalls;
void setup() {
size(400, 400);
smooth();
frameRate(30);
// setting up the space for 3 moving balls
numBalls = 10;
balls = new MovingBall[numBalls];
// setting up the startup values for the balls in the array
for (int i = 0; i < numBalls; i++) {
balls[i] = new MovingBall();
balls[i].x = random(0, width);
balls[i].y = random(0, height);
balls[i].w = random(15, 35);
balls[i].maxW = balls[i].w;
balls[i].speed = 0;
balls[i].movingForward = true;
balls[i].movingUp = true;
balls[i].expanding = false;
balls[i].mouseInside = false;
balls[i].r = random(0, 255);
balls[i].g = random(0, 255);
balls[i].b = random(0, 255);
}
fill(127);
noStroke();
}
void mouseMoved() {
}
void draw() {
background(255);
fill(0);
for (int i = 0; i < numBalls; i++) {
balls[i].drawItself();
balls[i].update();
balls[i].check();
}
for (int i = 0; i < numBalls; i++) {
float d = sqrt(pow((mouseX - balls[i].x), 2) + pow((mouseY - balls[i].y), 2));
if (d < balls[i].w/2)
balls[i].mouseInside = true;
else
balls[i].mouseInside = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment