Classes + Collision Detection

icm05-classes

A class is an object composed of data and functions to create different behaviors.
This week I had to define a class, send it to a partner and incorporate my partner’s class into a new sketch to communicate with mine.

I designed an abstract bird moving and bouncing through the screen, and my partner Zhen Liu created an array of balls. I put them together in my sketch and decided to make the balls react when the bird approaches them. This function is written inside the “Ball” class as void check(Bird myBird) containing the code that sets the behavior.

Main Sketch:

//DECLARE Bird myBird; Ball[] ball=new Ball[10]; void setup() { size(600, 600); smooth(); //INITIALIZE myBird = new Bird(0, 0); for (int i=0; i


Bird Class:

class Bird { // GLOBAL VARIABLES float x; float y; float speedx = 4; float speedy = 0.5; // CONSTRUCTOR Bird(float _x, float _y) { x=_x; y=_y; } // FUNCTIONS void display() { noStroke(); fill(random(255), random(255), 0, 200); triangle(x, y, random(x-100, x+100), random(y-100, y+100), random(x-150, x+150), random(y-150, y+150)); } void move() { x += speedx; y += speedy; } void bounce() { if (x > width || x < 0) { speedx = speedx * -1; } if (y > height || y < 0) { speedy = speedy * -1; } } void gravity() { speedy += 0.2; } }


Ball Class:

class Ball { float x, y, v, r=60; //still need r //and make it move in circle Ball(float x_, float y_) { x=x_; y=y_; v=5; } void move() { x=x+v; println(x); } void bounce() { if (x<0||x>width||y<0||y>height) { v=-v; } } void display() { noStroke(); fill(80, 150, 205, 100); ellipse(0, 0, r, r); } /* void zoom() { translate(x, y); if (mousePressed==true) { scale(random(2, 3)); fill(random(0, 255), random(100, 150), random(200, 255), 80); } }*/ void check(Bird myBird) { translate(x, y); float d = dist(x, y, myBird.x, myBird.y); if (d <= 100) { scale(random(2, 3)); fill(random(0, 255), random(100, 150), random(200, 255), 80); } } }

Leave a Reply