We are about to switch to a new forum software. Until then we have removed the registration on this forum.
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!
Answers
damn it, double post :-?
Per pixel collision detection is a very time consuming activity and can seriuosly affect performance if over used.
A suitable algorithm would be
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: