intersect/collision with bitmap and rectangles

769 Views Asked by At

I've been trying to write code when the coordinates cx/cy intersect with a rectangle/s the rectangle changes color. This has been driving me up the wall. Here is my code for the rectangles.

for(int k = 0; k<=15; k++){
        k = k * 55;
        for(int i=0;i<=9;i++){
             i = i*55;  
             bounds.set(left+i,top+k,right+i,bottom+k);
             paint.setColor(Color.WHITE);
             canvas.drawRect(bounds, paint);
             if (cx == left || cx == right || cy==top|| cy == bottom){
                 paint.setColor(Color.DKGRAY);
                 canvas.drawRect(bounds, paint);
             }
             i=i/55;
            }    
        k = k/55;
    }   
2

There are 2 best solutions below

1
On BEST ANSWER

Are you trying to inflate a rectangle, and change color when the intersection occurs?

Note that the values of left, right, top and bottom never actually change, so the if the check doesn't trigger in the first iteration of the loop, it never will.

Also, note that, in the case where it does intersect, it will set the color to DKGRAY, but then set it straight back to WHITE again on the next loop. Is this what you want?

I think you mean to do something like this. Here, we are comparing with the actual changing values.

for(int k = 0; k<=15; k++){
    k = k * 55;
    for(int i=0;i<=9;i++){
         i = i*55;  
         int boundsLeft = left + i;
         int boundsTop = top + k;
         int boundsRight = right + i;
         int boundsBottom = bottom + k;
         bounds.set(boundsLeft, boundsTop, boundsRight, boundsBottom);
         paint.setColor(Color.WHITE);
         canvas.drawRect(bounds, paint);
         if (cx == boundsLeft|| cx == boundsRight || cy==boundsTop || cy == boundsBottom ){
             paint.setColor(Color.DKGRAY);
             canvas.drawRect(bounds, paint);
         }
         i=i/55;
        }    
    k = k/55;
}   
0
On
             for(int i=0;i<=9;i++){
             i = i*55;  
             int boundsLeft = left + i;
             int boundsTop = top + k;
             int boundsRight = right + i;
             int boundsBottom = bottom + k;
             bounds.set(boundsLeft, boundsTop, boundsRight, boundsBottom);
             if(boxes[k][i]==0){
                 paint.setColor(Color.GREEN);
                 canvas.drawRect(bounds, paint);
             }
             else{
                 paint.setColor(Color.DKGRAY);
                 canvas.drawRect(bounds, paint);
             }
             if (cx >= boundsLeft && cx <= boundsRight && cy>=boundsTop && cy <= boundsBottom ){
                 plow.set(boundsLeft, boundsTop, boundsRight, boundsBottom);
                 paint.setColor(Color.DKGRAY);
                 canvas.drawRect(plow, paint);
                 boxes[k][i]=1;
             }
              i=i/55;

            }