Classes

I followed this tutorial to learn about classes

A class is a way of constructing something, it doesn’t specify one specific thing just how you go about building it. You have to construct a class and then create a class instance which is the specifics within the class which call the object in and tell it how to behave.

In this tutorial I learnt how to build a class where the class instance was a ball that bounces in the window.

Ball myBall; //Declares the class then class instance 
Ball myBall2;
Ball myBall3;
void setup(){
 size(600,600);
 smooth();
 
 myBall = new Ball(200,200); //Initializes the class. New is saying create a new instance of the class 'Ball'
myBall2 = new Ball(100,400);
myBall3 = new Ball(400,200);
}
void draw(){
 
 background(0,50,50);
 
 myBall.run(); //Calls the function of the class. The '.' opens up the class. 
 myBall2.run();
 myBall3.run();
 
 
}
class Ball {
//global variables. location, speed...
 float x=0;
 float y=0;
 float speedX = 4;
 float speedY = 0.5;
//constructor. how to build the class, calling variables, happens just once.
 Ball(float _x, float _y) {
x = _x;
 y = _y;
 }
 //functions.
 void run() {
 display();
 move();
 bounce();
 gravity();
 }
void gravity() {
 speedY += 0.2;
 }
 
 void bounce() {
if (x > width) {
 speedX = speedX * -1;
 }
 if (x < 0) {
 speedX = speedX * -1;
 }
 if (y > height) {
 speedY = speedY * -1;
 }
 if (y < 0) {
 speedY = speedY * -1;
 }
 }
 void move() {
 x += speedX;
 y += speedY;
 }
 void display() {
 strokeWeight(4);
 stroke(255);
 fill(154,54,154);
 ellipse(x, y, 30, 30);
 
 }
}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s