Skip to content

Instantly share code, notes, and snippets.

@denkspuren
Created November 29, 2014 12:16
Show Gist options
  • Save denkspuren/4937128f44f57ae00e74 to your computer and use it in GitHub Desktop.
Save denkspuren/4937128f44f57ae00e74 to your computer and use it in GitHub Desktop.
Bird and Balloons with Inheritance
class FlyingObject {
float w, h;
float x, y;
FlyingObject(float x, float y, float w, float h) {
this.x = x; this.y = y; this.w = w; this.h = h;
}
void display() {
ellipse(x,y,w,h);
}
}
class HFlyer extends FlyingObject {
HFlyer(float x, float y, float w, float h) {
super(x,y,w,h);
}
void move(float vx) {
x -= vx;
}
boolean visible() {
return (x+w/2 > 0) && (x-w/2 < width);
}
}
class VFlyer extends FlyingObject {
VFlyer(float x, float y, float w, float h) {
super(x,y,w,h);
}
void move(float vy) {
y -= vy;
}
boolean visible() {
return (y+h/2 > 0) && (y-h/2 < height);
}
}
class Bird extends HFlyer {
Bird(float x, float y, float w, float h) {
super(x,y,w,h);
}
boolean intersects(Balloon balloon) {
// formula for intersection of ellipses is no fun
return dist(balloon.x,balloon.y,x,y) <= balloon.w/2 + w/2;
// && get(int(x-w),int(y)) == color(255);
}
}
class Balloon extends VFlyer {
Balloon(float x, float y, float w, float h) {
super(x,y,w,h);
}
void poof() {
y = height + h/2;
}
}
Balloon[] balloons = new Balloon[10];
Bird bird;
void setup() {
size(400,300);
for(int i=0; i<balloons.length; i++) {
balloons[i] = new Balloon(random(0,width),random(0,height),30,30);
}
}
void draw() {
background(128);
for(int i=0; i<balloons.length; i++) {
balloons[i].display();
balloons[i].move(0.3);
if (bird != null && bird.intersects(balloons[i])) {
balloons[i].poof();
continue;
}
if (!balloons[i].visible())
balloons[i].y = height+balloons[i].h/2;
}
if (bird != null) { // What if 'if' is missing
bird.display();
bird.move(2.0);
}
}
void mouseClicked() {
if (mouseY > 0 && mouseY < height)
bird = new Bird(width-30,mouseY,30,10);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment