Balls Bouncing problem

I am trying to create bouncing ball effect with some walls. The problem is balls are not reflecting properly from these walls. Here is the code. You need to click and drag to create box.

ArrayList<DrawRect> test = new  ArrayList();
ArrayList<Ball> balltest = new  ArrayList();
void setup() {
  size(500, 500);
  for (int i=0; i<20; i++) {
    Ball B = new Ball((int)random(width), (int)random(height), (int)random(4, 20));
    balltest.add(B);
  }
}

void draw() {
  background(-1);
  for (Ball B : balltest) {
    B.show();
    B.move();
  }
  for (DrawRect Box : test) {
    Box.show();
  }
}
int x, y, w, h; 
void mousePressed() {
  x = mouseX; 
  y = mouseY;
}
void mouseDragged() {
  w = mouseX; 
  h = mouseY;
}
void mouseReleased() {
  test.add(new DrawRect(x, y, abs(x-w), abs(y-h)));
}

Class

class Ball {
  int x, y, r, dx, dy;
  int i=1, j=1;
  Ball(int x, int y, int r) {
    this.x = x;
    this.y = y;
    this.r = r;
    dx = (random(50)<25)?-1:1;
    dy = (random(50)<25)?-1:1;
  }

  void show() {
    fill(#FA0505);
    noStroke();
    ellipse(x, y, 2*r, 2*r);
  }

  void move() {
    x+=dx*i;
    y+=dy*j;
    if (x<r || x>width-r)i=-1*i;
    if (y<r || y>height-r)j=-1*j;
    for (DrawRect Box : test) {
      if (x>Box.x-r && x<Box.x+Box.w+r) {
        if (y>Box.y-r && y<Box.y+Box.h+r)  i=-1*i;
      } else if (y>Box.y-r && y<Box.y+Box.h+r) {
        if (x>Box.x-r && x<Box.x+Box.w+r)  j=-1*j;
      }
    }
  }
}


class DrawRect {
  int x, y, w, h;
  DrawRect(int x, int y, int w, int h) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
  }

  void show() {
    fill(#B0FA05);
    noStroke();
    rect(x, y, w, h);
  }
}

Answers

Sign In or Register to comment.