Hi,
Am to trying to implement pixel perfect collision detection in android. I have came
across some articles about this pixel perfect detection but am unable to implement them practically. Actually what am doing is: taking 2 bitmap's pixels into arrays. And then trying to take pixels in overlap region. But am confused about
how to get pixels of that overLap section. Can any one provide some help on this.
Am having 2 image objects which are bounded by rectangles. Those two image objects are animated.I want to change
some state when those two image objects are collided. This is the code am trying.
public static boolean detectCollision(Ball ball,Sprite bat,int currentFrame)
{
try
{
int left1,left2,top1,top2,right1,right2,bottom1,bottom2;
left1=ball.ballLeft;
top1=ball.ballTop;
right1=ball.ballRight;
bottom1=ball.ballBottom;
left2=bat.batLeft;
top2=bat.batTop;
right2=bat.batRight;
bottom2=bat.batBottom;
if(bottom1<top2)>
return false;
if(right1 < left2)
return false;
if (top1 > bottom2)
return false;
if (left1 > right2)
return false;
int overLap_left,overLap_top,overLap_right,overLap_bottom;
overLap_left=Math.max(left1,left2);
overLap_top= Math.min(top1, top2);
overLap_right=Math.max(right1, right2);
overLap_bottom=Math.min(bottom1, bottom2);
if (overLap_right <= overLap_left || overLap_bottom <= overLap_right) {
return false;
}
int width,height;
width=overLap_right-overLap_left;
height=overLap_bottom-overLap_top;
Bitmap bmp1=((BitmapDrawable) ResourceCollection.ballCollection.get(currentFrame).getCurrent()).getBitmap();
Bitmap batImage=((BitmapDrawable) ResourceCollection.batCollection.get(0).getCurrent()).getBitmap();
int[] pixels1 = new int[bmp1.getWidth()*bmp1.getHeight()];
int[] pixels2 = new int[batImage.getWidth()*batImage.getHeight()];
bmp1.getPixels(pixels1, 0, bmp1.getWidth(), 0,0, bmp1.getWidth()-1, bmp1.getHeight()-1);
batImage.getPixels(pixels2, 0, batImage.getWidth(),0,0, batImage.getWidth()-1, batImage.getHeight()-1);
for(int X=overLap_left;X<overlap_right;x++)>
{
for(int Y=overLap_top;Y<overlap_bottom;y++)>
{
int x;
if (X >XandY.X)
x = X - XandY.X;
else
x = XandY.X - X;
int y;
if (Y > XandY.Y)
y = Y - (int) XandY.Y;
else
y = XandY.Y - Y;
if(x>=bmp1.getWidth() || y>=bmp1.getHeight())
return false;
if(x>=batImage.getWidth() || y>=batImage.getHeight())
return false;
int a=bmp1.getPixel(x, y);
int b=batImage.getPixel(x, y);
if (a != 0 && b != 0)
{
return true;
}
}
}
return false;
}
catch(Exception ee)
{
String msg=ee.getMessage();
Log.v("Error", ee.getMessage());
return false;
}
How can i check that the two images are touched each other in the Intersection rectangle(Overlapping region).?