Class 22 exercise (OOP) – May 2nd – Skyler Liu

Video:

Code:

ArrayList<Ball> balls;
int ballWidth = 28;

void setup() {
size(640, 360);
noStroke();
balls = new ArrayList<Ball>();
balls.add(new Ball(width/2, 0, ballWidth));
}

void draw() {
background(255);
for (int i = balls.size()-1; i >= 0; i–) {
Ball ball = balls.get(i);
ball.move();
ball.display();
}
}

void mousePressed() {
balls.add(new Ball(mouseX, mouseY, ballWidth));
}

class Ball {

float x;
float y;
float speedX;
float speedY;
float w;
color c;

Ball(float tempX, float tempY, float tempW) {
x = tempX;
y = tempY;
w = tempW;
speedX = random(-5, 5);
speedY = random(-5, 5);
c = color(random(100, 255), random(100, 255), random(100, 255));
}

void move() {

x = x + speedX;
if ((x > width) || (x <0)) {
speedX = speedX * -1;
}

y = y + speedY;
if ((y > height) || (y < 0)) {
speedY = speedY * -1;
}
}

void display() {
fill(c);
ellipse(x,y,w,w);
}
}

Process:

In the previous recitation, I made a single bouncing ball which could change color following mouse press and I wanted to make a program which could store several balls at the same time, but my knowledge was not enough. In today’s course, I have learned the key to achieve my ideal before, so I made this program after class.

Leave a Reply