bool Sprite::pixCollision(const Sprite& other) const { // If bounding rectangles do not intersect, sprites // do not collide if (!rect.intersects(other.getBox())) { return false; } else { Rectf inter = intersection(other.getBox()); // Loop over region int height = (int)(inter.Height()); int width = (int)(inter.Width()); int xOff = (int)(inter.MinX() - pos.X()); int xOffOther = (int)(inter.MinX() - other.getPos().X()); int yOff = (int)(inter.MinY() - pos.Y()); int yOffOther = (int)(inter.MinY() - other.getPos().Y()); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { // If pixel in current cell at (i, j) is non-transparent // for both sprites, then they do intersect bool thisIsTransparent = sheets[animations[current.X()].first.X().X()]->isPixTransparent( currentCell, j + xOff, i + yOff); bool otherIsTransparent = other.getSheet().isPixTransparent( other.currentCell, j + xOffOther, i + yOffOther); if (!thisIsTransparent && !otherIsTransparent) { return true; } } } // All pixels in region checked, there is no intersection return false; } }
Rectf Sprite::intersection(const Rectf &box) const { if (!rect.intersects(box)) { return Rectf(); } else { return Rectf( max(rect.MinX(), box.MinX()), // Min X min(rect.MaxX(), box.MaxX()), // Max X max(rect.MinY(), box.MinY()), // Min Y min(rect.MaxY(), box.MaxY()) ); // Max Y } }