Per pixel collision detection

edited April 2014 in How To...

Hello everyone!

I'm trying to figure out how to write a function for per pixel collision detection. I'm making a space shooter, and since the images for the player ship and the enemy ship are squares the hitboxes are not so accurate.

I understand the concept of per pixel collision detection, but all the examples I've found are in either c# or XNA.

I've written a short test program, and I imagine the code would work something like this:

PImage player;
PImage enemy;
boolean enemyalpha = true;
boolean playeralpha = true;
boolean touch = false;

void setup(){
  size(600,600);
  player = loadImage("IMGplayership.png");
  enemy = loadImage("IMGenemyship.png");
  imageMode(CENTER);
}

void draw(){
  if(touch == false){background(0);}
  else{background(255);}
  image(player,mouseX,mouseY);
  image(enemy,width/2,height/2);

  for(int ie = 0; ie < enemy.pixels.length; ie++){
      is the pixel NOT transparent, set enemyalpha = false;

      for(int ip = 0; ip < player.pixels.length; ip++){ 
        is the pixel NOT transparent, set playeralpha = false;
      }

      if(enemyalpha == false && playeralpha == false){
        if(the pixels are at the same place){
        touch == true;
        }
      }   
  }

}

Anyone got experience from per pixel collision detection?

All the best!

Tagged:

Answers

  • damn it, double post :-?

  • edited April 2014 Answer ✓

    Per pixel collision detection is a very time consuming activity and can seriuosly affect performance if over used.

    A suitable algorithm would be

    If the two image rectangles overlap then
      Calculate the coordinates of overlap (will be a rectangle)
      For each position in the overlap rectangle
        If the corresponding pixels in both images are both opaque then
          End comparison and return true
      End for loop
      Return false
    Else (no overlap)
      Return false
    

    You might look at the Sprites library it gives you a choice of collision detection including pixel collision. It also provides a framework for using sprites.

  • with the help from my teacher we wrote this function for per pixel collision, if someone is looking for something similar:

    boolean intersectPixels(int x1, int y1, int w1, int h1, color[] data1, int x2, int y2, int w2, int h2, color[] data2){
    
      int top = max(Y1, Y2);
      int bottom = min(Y1+h1, Y2+h2);
      int left = max(X1, X2);
      int right = min(X1+w1, X2+w2);
    
      for(int y = top; y < bottom; y++){
    
        for(int x = left; x < right; x++){
    
          color color1 = data1[(x - X1) + (y - Y1) * w1];
          color color2 = data2[(x - X2) + (y - Y2) * w2];
    
          if(alpha(color1) != 0 && alpha(color2) != 0){
            return true; 
          }   
        }
      }
      return false;
    }
    
Sign In or Register to comment.