bool PixelPerfect(MyClass A, MyClass B)
// MyClass::getGlobalBounds(); just means the same as MyClass::sprite::getGlobalBounds();
// MyClass::GetImg(); returns a reference to static sf::Image variable in class (loaded at the beginning of app)
{
if( A.getGlobalBounds().intersects(B.getGlobalBounds()) ) //if sprites intersect, do pixel perfect test
{
int RectLeft = static_cast<int> ( max(A.getGlobalBounds().left , B.getGlobalBounds().left) );
int RectRight = static_cast<int> ( min(A.getGlobalBounds().left + A.getGlobalBounds().width , B.getGlobalBounds().left + B.getGlobalBounds().width) );
int RectBottom = static_cast<int> ( min(A.getGlobalBounds().height + A.getGlobalBounds().top , B.getGlobalBounds().height + B.getGlobalBounds().top) );
int RectTop = static_cast<int> ( max(A.getGlobalBounds().top , B.getGlobalBounds().top) );
sf::IntRect Rect(RectLeft, //collision rectangle
RectTop,
RectRight - RectLeft,
RectBottom - RectTop);
int LocalLeftA = RectLeft - static_cast<int> (A.sprite.getPosition().x); //local coordinates of Rect (referring to A and B),
int LocalTopA = RectTop - static_cast<int> (A.sprite.getPosition().y); //they will be used to refer to pixel positions in sf::Image
int LocalLeftB = RectLeft - static_cast<int> (B.sprite.getPosition().x); //as they are the same (if not scaled)
int LocalTopB = RectTop - static_cast<int> (B.sprite.getPosition().y);
for(int i=0; i<Rect.width; i++)
{
for(int j=0; j<Rect.height; j++)
{
if (A.GetImg().getPixel(i+LocalLeftA , j+LocalTopA).a > 0 && B.GetImg().getPixel(i+LocalLeftB , j+LocalTopB).a > 0)
{
return 1; //pixel intersection
}
}
}
return 0; //only bounding boxes intersection, no pixel
}
else return 0; //no bounding boxes intersection
}