Skip to content

Instantly share code, notes, and snippets.

@slambert
Created October 6, 2015 15:29
Show Gist options
  • Save slambert/5854a8474177ff3b029d to your computer and use it in GitHub Desktop.
Save slambert/5854a8474177ff3b029d to your computer and use it in GitHub Desktop.
A sketch thet uses objects and classes with two bouncing balls
// A sketch thet uses objects and classes with two bouncing balls
// Steve Lambert
// declare objects
Ball ball1;
Ball ball2;
// initialize variables
float gravity = 0.1; // gravity!
void setup() {
size(400,400);
ellipseMode(CENTER);
ball1 = new Ball(color(255,0,0,50),20); // color and size
ball2 = new Ball(color(0,0,255,50),20);
smooth();
}
void draw() {
background(255);
ball1.display();
ball1.move();
ball2.display();
ball2.move();
if (ball1.intersect(ball2)) {
// ball1.xSpeed = ball1.xSpeed * -1;
// ball2.xSpeed = ball2.xSpeed * -1;
// ball1.ySpeed = ball1.ySpeed * -1;
// ball2.ySpeed = ball2.ySpeed * -1;
background(200); // grey the background so I can tell they are touching
ball1.display(); // and continue
ball1.move();
ball2.display();
ball2.move();
}
}
//change the ySpeed when the key is pressed
// this causes the balls to become hot air balloons
void keyPressed() {
ball1.ySpeed = -6;
ball2.ySpeed = -4;
}
// The below can be put in another tab, or not.
class Ball { //defining the class
// variables
color c;
float dim;
float locX = 0; // location X
float locY = 100; // location Y
float xSpeed = 1; // Speed on X axis
float ySpeed = 1; // Speed on Y axisv
// constructor
Ball(color c_, float dim_) {
noStroke();
c = c_;
dim = dim_;
locX = random(width);
locY = random((height/2),height);
}
void display() {
//draw the circle
fill(c);
ellipse(locX,locY,dim,dim);
}
void move() {
ySpeed = ySpeed + gravity; // speed on y axis is affected by gravity, always pushing down
xSpeed = xSpeed *.995; // inertia
// if object gets to the edge, go the other way.
if ((locX >= width-(dim/2)) || (locX <= (dim/2))){
xSpeed = xSpeed * -1;
}
if (locY > height-((dim/2)+1)){
ySpeed = ySpeed * -.75; // ball bounces less each time
}
if (mousePressed) {
locX = mouseX;
locY = mouseY;
xSpeed = int(random(-3,3));
ySpeed = int(random(-3,3));
}
locX = locX + xSpeed;
locY = locY + ySpeed;
locX = constrain(locX,0+(dim/2),width-(dim/2));
locY = constrain(locY,0+(dim/2),height-(dim/2));
}
// A function that returns true or false based on whether two Ball objects intersect
boolean intersect(Ball b) {
float distance = dist(locX,locY,b.locX,b.locY); // Calculate distance
if (distance < (dim/2) + (b.dim/2)) {
return true;
} else {
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment