We are about to switch to a new forum software. Until then we have removed the registration on this forum.
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
please explain Ball.move() to us
He has used enhanced for loop to call box arrayList() [ **test ** ] inside the ball.move() function to test the ball collision with the boxes.
I am not sure but it can slow down the program.
i'm more curious about the conditions. i want to know what he wants to do and how that code implements what he wants to do. i am applying the 'tell it to the bear' principle:
http://talkaboutquality.wordpress.com/2010/08/30/tell-it-to-your-teddy-bear/