collision detection in a class
in
Programming Questions
•
1 year ago
Hello,
I am trying to figure it out how to check collision detection outside the class, but it seems not to be working. Here is what I came up with:
- //Ball ball1;
- Ball [] balls = new Ball [50];
- void setup() {
- size(500, 500);
- for (int i=0; i < balls.length; i++) {
- int x = int(random(30, 300));
- int y = int(random(20, 400));
- int speedX = int(random(1, 10));
- int speedY = int(random(1,10));
- color filler1 = color(random(0,255),0,0);
- int diam = int(random(20,50));
- balls[i] = new Ball(x, y, speedX, speedY, diam, filler1);
- // ball1 = new Ball(50,100,2,40);
- // ball2 = new Ball(0,300,5,100);
- }
- }
- void draw() {
- background(255);
- for (int i=0; i < balls.length; i++) {
- balls[i].animate();
- balls[i].display();
- }
- for (int j = 0; j < balls.length; j++){
- for( int k = 0; k < balls.length; k++){
- if( dist(balls[j].posX, balls[j].posY, balls[k].posX, balls[k].posY) >= diam[j] + diam[k]){
- ballSpeedX[j] *= -1;
- ballSpeedY[j] *= -1;
- }
- }
- }
- }
And this is for the class
- class Ball {
- int posX;
- int posY;
- int ballSpeedX;
- int ballSpeedY;
- int ballDiam;
- color filler;
- Ball(int tempPosX, int tempPosY, int tempBallSpeedX, int tempBallSpeedY, int tempBallDiam, int tempFiller) {
- posX = tempPosX;
- posY = tempPosY;
- ballSpeedX = tempBallSpeedX;
- ballSpeedY = tempBallSpeedY;
- filler = tempFiller;
- ballDiam = tempBallDiam;
- }
- void display() {
- fill(filler);
- ellipse(posX, posY, ballDiam, ballDiam);
- }
- void animate() {
- posX += ballSpeedX;
- posY += ballSpeedY;
- if (posX > width-ballDiam || posX <= 0+ballDiam) {
- ballSpeedX = -ballSpeedX;
- }
- if(posY > height-ballDiam || posY <= 0+ballDiam){
- ballSpeedY = -ballSpeedY;
- }
- }
- }
1