sorry / other timezone /
-a- your ( xy ± npx ) is a result of not having clean position for each rectangle.
so i want you again to check my above ( ready code ) for the “make” bricks
-b- for ball / rect collision are many ways,
basic should be a OVER RECT
a concept you need again and again with processing
like mouse over rect ( button )…
we make a boolean function:
boolean overRect(float mx, float my, int x, int y, int w, int h) {
return ( mx > x && mx < x + w && my > y && my < y + h ) ;
}
this returns true if the POINT at ( mx,my )
is over a rect(x,y,w,h)
ha, but a ball is not a point, it has a radius, what we do?
the ball hits the rect actually “earlier” by br
so we just think that the rect is BIGGER by br ON ALL SIDES
with this a hit condition would be
circle(bx,by,2*br);
rect(rx,ry,rw,rh);
// println( overRect(bx,by,rx,ry,rw,rh) ); // point thinking
println( overRect(bx,by,rx-br,ry-br,rw+2*br,rh+2*br) ); // ball radius >> bigger rect / thinking
all this works only if you NOT use rectMode(CENTER);
complete test code
int rx=20, ry=30, rw=60, rh=40;
int bx, by, br=10;
void setup() {
noFill();
}
void draw() {
background(200, 200, 0);
bx = mouseX;
by=mouseY;
circle(bx, by, 2*br);
rect(rx, ry, rw, rh);
// println( overRect(bx,by,rx,ry,rw,rh) ); // point thinking
println( overRect(bx, by, rx-br, ry-br, rw+2*br, rh+2*br) ); // ball radius >> bigger rect / thinking
}
boolean overRect(float mx, float my, int x, int y, int w, int h) {
return ( mx > x && mx < x + w && my > y && my < y + h ) ;
}
-c-
but you want also a change of speed of the ball, depending on what side of the rect it hits?
a easy first way can be ( later make it shorter and also check on the rect edges hit… )
for (int i=0; i < 50; i++) {
if (blocks[i]==1) {
rect(rx[i], ry[i], rw, rh);
if ( overRect(bx,by,rx[i]-br,ry[i]-br,rw+2*br,rh+2*br) ) {
println("over block: "+i);
blocks[i]=0; //_disable
if ( by > ry[i] + rh ) ySpeed *= -1; // println("// ball come from bottom");
if ( by < ry[i] ) ySpeed *= -1; // println("// ball come from top");
if ( bx < rx[i] ) xSpeed *= -1; // println("// ball come from left");
if ( bx > rx[i] + rw ) xSpeed *= -1; // println("// ball come from right");
}
}
}