Array Moving balls.
in
Programming Questions
•
1 year ago
Basically I'm trying to create a simple program with arrays to make random balls move randomly around the screen, bouncing off the border but stop when they touch. I need the radius of each ball to be randomly set to between 20 and 40 (inclusive). Each of the horizontal speed and the vertical speed of a ball, I want randomly set to be between -5 and +5. Also the colour random.. Could anyone help me? I'm very new to processing and this is what I have at this time.
class Ball {
int rad; // radius
int x,y; // center's position of the ball
int speedx; // for horizontal speed
int speedy; // for vertical speed
color c; // color of the ball
// constructor for initialization
Ball() {
// write some code
}
// display a ball with the given x, y and rad, filled with c
void display() {
fill(c);
noStroke();
ellipse(x, y, rad*2, rad*2);
}
// set the new position according to speedx and speedy
// and check if a bounce happens
void moveBall() {
// write some code
}
// dispaly a ball and let it move
void play() {
display();
moveBall();
}
// check if collision happens
// returns true two balls collide; otherwise returns false
boolean collideWith(Ball other) {
float gap = dist(x, y, other.x, other.y);
if (gap <= rad + other.rad)
return true;
else
return false;
}
}
// don't change anything below
Ball b1, b2;
void setup() {
size(400, 400);
b1 = new Ball();
b2 = new Ball();
smooth();
}
void draw() {
background(255);
if (b1.collideWith(b2)) {
b1.display();
b2.display();
}
else {
b1.play();
b2.play();
}
}
1