Hi.
I'm writing a code, which performs pixel perfect collision check.
It creates sf::Rect which is rectangle of collision.
Then it transforms its coordinates to sprites' local (referring it to 0,0 points of both sprites).
Then I can use those coordinates to choose pixels in sf::Image entities which are created from the same texture as sprites (it has to be sf::Image because spirtes don't have getPixel method) and check their alpha channels.
And it works perfectly fine until i try to scale my sprites in main loop. Then coordinates in sprite don't match coordinates in image, because one of them is scaled.
How do I manage this? Should I somehow scale sprite back to it's original size at the beginning of function?
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
}