// define gravity
float gravity = 0.98;
int lastSecond;
int spawnNum;
// define a array to manage balls
ArrayList<Ball> balls = new ArrayList<Ball>();
Paddle paddle = new Paddle(new PVector(300,240));
void setup(){
// Initialize screen resolution
size(600, 480);
noStroke();
lastSecond = second();
// spwan a new ball at beginning
SpawnNewBall(1);
}
void draw(){
background(0);
// show total balls
fill(255);
textSize(18);
text("Total balls:" + balls.size(), 10, 30);
//// if time has passed 1 second
if(lastSecond != second()){
lastSecond = second();
// chance to spawn new ball
if(random(0,100) < 50){
// spawn new ball
SpawnNewBall(int(random(1,3 + spawnNum)));
spawnNum++;
}
}
// Draw Paddle
paddle.SetPosition(new PVector(mouseX,450));
paddle.Update();
// draw balls
for (int i = balls.size() - 1; i >= 0; i--) {
Ball ball = balls.get(i);
ball.Update();
// check if the ball hits paddle
if(CheckWithin(ball.position.x, paddle.position.x - paddle.size.x / 2, paddle.position.x + paddle.size.x / 2) &&
CheckWithin(ball.position.y, paddle.position.y - paddle.size.y / 2, paddle.position.y + paddle.size.y / 2)){
// if it hits the paddle
ball.SetVelocity(new PVector(ball.velocity.x, abs(ball.velocity.y) * -1));
}
// check if the ball fell under
if(ball.position.y > height + 50){
// destory the ball
balls.remove(ball);
ball = null;
}
}
}
void SpawnNewBall(int num){
// spawn new balls based on given number
for(int i=0; i< num; i++){
balls.add(new Ball(new PVector(random(0 ,width), random(-200,0)), new PVector(random(-10,10),0), 20));
}
}
boolean CheckWithin(float val, float min, float max){
if(val >= min && val <= max){
return true;
}
return false;
}class Ball{
PVector position, velocity;
color myColor;
float size;
Ball(PVector _pos, PVector _vel, float _size){
// Ball constructor
position = _pos;
velocity = _vel;
size = _size;
SetRandomColor();
}
void Update(){
// adds gravity
velocity.y += 0.98;
// apply velocity to the ball
position.add(velocity);
// collision detect
CollisionDetect();
// draw ball on the sceen
fill(myColor);
arc(position.x, position.y, size, size, 0, 2 * PI);
}
void CollisionDetect(){
// check x bounds
if(position.x + size > width ){
// hits bounds
velocity.x = -1 * abs(velocity.x);
} else if(position.x - size < 0){
velocity.x = 1 * abs(velocity.x);
}
}
void SetRandomColor(){
myColor = color(int(random(5,255)),int(random(5,255)),int(random(5,255)));
}
void SetVelocity(PVector velo){
velocity = velo;
}
}class Paddle{
color woodColor = color(163, 110, 32);
color myColor = color(226, 35, 24);
PVector position;
PVector size = new PVector(200,50);
Paddle(PVector pos){
position = pos;
}
void Update(){
noStroke();
// Draw handle
fill(woodColor);
rect(position.x - 25, position.y, 50, 80);
// Draw wood
arc(position.x, position.y, size.x, size.y, 0, 2 * PI);
// Draw paddle
fill(myColor);
arc(position.x, position.y, size.x - 20, size.y - 10, 0, 2 * PI);
}
void SetPosition(PVector pos){
position = pos;
}
}