[java] Pixel-Perfect Collision Detection

Started by
7 comments, last by TheBluMage 18 years, 9 months ago
Hey guys, I'm sure this has been talked about before, but I'm curious about how to implement pixel-perfect collision detection in Java. If anyone can help me out, even just by posting a link or two, that would be great. Thanks! - Rob
Advertisement
I don't know what u mean by pixel perfect; but in my game every entity have awt.Rectangle object for it's bounds. Rectangle is instatiated to size of it's sprite image (BufferedImage). When I'm updating position (I really use upper left corner for position no separate x,y variables), I move rectangle all the time. Then for collision testing between 2 entities in game all I have to do is to ask boolean b = ent1.bounds.intersects(ent2.bounds);

It seems to work perfectly correct in mine game, but maybe you are looking for something else?
What you describe is often a good-enough way for detecting collisions. Sometimes, though, it isn't good enough. If a game has highly irregular objects that can collide with others, bound rectangles are insufficient. That's where "pixel-perfect" collision detection comes in. The idea behind it has something to do with sprite masks and binary operators, but I'm not sure how it's (usually) implemented in Java. So that's what I'm wondering about. :P

Thanks anyways though,
Rob
Rectangle in java is subclass of Shapes which can be arbitrary polygons and even curves if you need such. I suggest you to take look into awt.Shape interface and classes that implements it. Also if you need more precision then ints, then check those classes with 2D suffixes, since those have float or double precision.

Maybe Polygon class is what you looking for? http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Polygon.html

Otherwise if you want to implement all intersection testing yourself get yourself a good book about collision detection :). Gino van der Bergen's is highly recomended:

http://www.amazon.co.uk/exec/obidos/ASIN/155860801X/qid=1120061481/br=3-2/br_lfncs_b_2/026-3423688-1146867
About this pixel perfect collision, I see other ppl use somewhat complicated procedure with mask and other stuff.
I don't know if mine is using wrong approach or not but it works perfectly for me.

First check with the basic rectangle collision check, if it's pixel collided of course it the bounding rectangle must be collided first, right!?

Now this is I use for pixel collision:
Get the intersection collision rectangle and check the pixels on both sprite image in that intersect part, if it's not transparent then it is collided.
public static boolean isPixelCollide(double x1, double y1, BufferedImage image1,                               double x2, double y2, BufferedImage image2) {  // initialization  double width1 = x1 + image1.getWidth() -1,         height1 = y1 + image1.getHeight() -1,         width2 = x2 + image2.getWidth() -1,         height2 = y2 + image2.getHeight() -1;  int xstart = (int) Math.max(x1, x2),      ystart = (int) Math.max(y1, y2),      xend   = (int) Math.min(width1, width2),      yend   = (int) Math.min(height1, height2);  // intersection rect  int toty = Math.abs(yend - ystart);  int totx = Math.abs(xend - xstart);  for (int y=1;y < toty-1;y++){    int ny = Math.abs(ystart - (int) y1) + y;    int ny1 = Math.abs(ystart - (int) y2) + y;    for (int x=1;x < totx-1;x++) {      int nx = Math.abs(xstart - (int) x1) + x;      int nx1 = Math.abs(xstart - (int) x2) + x;      try {        if (((image1.getRGB(nx,ny) & 0xFF000000) != 0x00) &&            ((image2.getRGB(nx1,ny1) & 0xFF000000) != 0x00)) {           // collide!!	   return true;	}      } catch (Exception e) {//      System.out.println("s1 = "+nx+","+ny+"  -  s2 = "+nx1+","+ny1);      }    }  }  return false;}

x1, y1 is the position of sprite 1
image1 is the image of sprite 1
x2, y2 is the position of sprite 2
image2 is the image of sprite 2

And to use it simply:
double x1, y1, x2, y2;BufferedImage image1, image2;if (rectangle collision) {  if (isPixelCollide(x1, y1, image1, x2, y2, image2)) {    // collide!  }}



Hope it helps!
-------------Golden T Game Engine - Java Game EngineGolden T Website | Golden T Forum
Yes that's basically what I'm looking for! Good job!

Question: why do you subtract each double by one?

- Rob
Role's method is fine. For better performance, you can also pre-create bitmasks out of your alpha values (i.e. 1 bit=alpha value) and use bitwise arithmetic to check for collisions, that will require less memory accesses during the test.
Here a link: Allegro tutorials, there is an archive ppcol.zip with a file collide.c in it which demonstrates the algorithm.
Umm I forgot why I'm substract the width and height by 1, perhaps because BufferedImage.getRGB(width, height) is throwing exception, it must be size-1.
Not sure though.
Just uncomment the print out, and remove the substraction, and see if it's indeed throwing exception or not.
I don't know about performance but it should be fast enough, cos it only perform pixel collision if it passed the rectangle collision, so not every loop it checks for pixel collision.
-------------Golden T Game Engine - Java Game EngineGolden T Website | Golden T Forum
Also some good tutorials here at GameDev that might help you out.

This topic is closed to new replies.

Advertisement