In this recitation, I participated in the Object-Oriented Programming workshop with Tristan. We focused on adding classes to code in order to make the code more clean and simple to bring back up. Classes (the function in processing) were split into three parts, the variables, the constructor, and the functions of each class.
Here is the example code we created (with my small edit of interaction by adding a mousePressed function:
The Ball Class:
class Ball { float x, y; color c; float spdX, spdY; float r; Ball(float newSpdX, float newSpdY, color newColor) { r = 50; spdX = newSpdX; spdY = newSpdY; c = newColor; x = width/2; y = height/2; } void move() { if (mousePressed){ x += spdX; y += spdY; } } void display() { fill(c); ellipse(x, y, r, r); } }
And the Main Code calling the class:
Ball james; Ball jame; ArrayList<Ball> ballList = new ArrayList<Ball>(); void setup() { size(1600,900); for(int i=0; i<100; i++) { ballList.add(new Ball(random(-10,10),random(-10,10),color(random(255)) )); } //james = new Ball(random(-10,10),random(-10,10),color(random(255)) ); //jame = new Ball(5, 0, color(0,0,255)); } void draw() { background(255,255,150); //james.display(); //jame.display(); //james.move(); //jame.move(); for(int i = 0; i<ballList.size(); i++) { Ball temp = ballList.get(i); temp.display(); temp.move(); } }
For my version, I wanted to change the balls to squares first, and then make them fall from the top of the screen using (mousePressed).
I also wanted to change the Squares to rain down in a funnel-like shape, instead of spreading from the middle. So here is what it looked like:
And here is the new code:
For the class:
class Square { float x, y; color c; float spdX, spdY; float size; Square(float newSpdX, float newSpdY, color newColor) { size = 50; spdX = newSpdX; spdY = newSpdY; c = newColor; x = width/2; y = 0; } void move() { if (mousePressed) { x += spdX; y += spdY; } } void display() { fill(c); rect(x, y, size, size); } }
For the main code:
Square james; ArrayList<Square> ballList = new ArrayList<Square>(); void setup() { size(1600,900); for(int i=0; i<100; i++) { ballList.add(new Square(random(-10,10),random(0,10),color(random(255)) )); } //james = new Ball(random(-10,10),random(-10,10),color(random(255)) ); //jame = new Ball(5, 0, color(0,0,255)); } void draw() { background(255,255,150); //james.display(); //jame.display(); //james.move(); //jame.move(); for(int i = 0; i<ballList.size(); i++) { Square temp = ballList.get(i); temp.display(); temp.move(); } }