Class and Collisions - beginner
in
Programming Questions
•
1 year ago
Hi all.
I am trying to write a program that will start with two random ellipses, at random diameters between 20,40 and at random positions and color with each start. The speed of the balls must be randomised between -5 and 5. If the two balls collide the program stops and if the balls hit any edges they are rebounded. I'm not sure how to go about adding collision detection to the balls or have them bounce off edges.
I have never used a 'class' before so I'm just not sure if I have implemented things correctly (constructor) along with the functions I have used and well probably many other things that are wrong.
Any help would be appreciated.
Thanks.
I am trying to write a program that will start with two random ellipses, at random diameters between 20,40 and at random positions and color with each start. The speed of the balls must be randomised between -5 and 5. If the two balls collide the program stops and if the balls hit any edges they are rebounded. I'm not sure how to go about adding collision detection to the balls or have them bounce off edges.
I have never used a 'class' before so I'm just not sure if I have implemented things correctly (constructor) along with the functions I have used and well probably many other things that are wrong.
Any help would be appreciated.
Thanks.
- Ball myBall;
void setup() {
size(400, 400);
myBall = new Ball(); //should this line be in the constructor for class ball?
smooth();
frameRate(200);
}
void draw() {
background(255);
myBall.display();
myBall.movingBall();
myBall.collision();
}
class Ball {
int radius;
int locX, locY;
int speedX, speedY;
color col;
//CONSTRUCTOR
Ball() {
speedX=int(random(-5, 5));
speedY=int(random(-5, 5));
col = int(random(0, 255)); //??? Color
radius = int(random(20, 40));
locY = int(random(0, 400));
locX = int(random(0, 400));
}
void display() {
ellipseMode(CENTER);
noStroke();
fill(col);
smooth();
ellipse(locX + speedX, locY + speedY, radius*2, radius*2);
}
void movingBall() {
if (locX >= width || locX <=0) {
speedX = -1;
}
if (locY >= height || locY <= 0) {
speedY = -1;
}
if (locX <= width) {
locX++;
}
if (locY <= height) {
locY++;
}
}
void collision() { // ????
}
}
1