'How to check if two rectangles, one is rotated, intersect in SFML

I have a rotated Rectangle inside a closed tile map of rectangles. What would be the best way to check if the player (which is the rotated rectangle) is intersecting with one of the rectangles of the tile map?

Picture from inside the game to better show what the map looks like:You can see the player (Blue rect) and the map borders (Red rects). The blue rect must not leave outside the red rectarea

If it matters, the Player's type is sf::Shape and the map's data is inside an int array.



Solution 1:[1]

SFML does not provide collision detection, it only has method to check if two axis-aligned rectangles intersect. If you need something more complex, you will have to implement if yourself.

If you don't need precision detection, you can test Sprite.getGlobalBounds().intersects(...) with the rectangle of the map. If you want ideal collision detection, you have more then one option:

  • Pixel perfect Collision. First check if bounding box intersect the map tile and them check all non-transparent pixels for collision. Not very fast but easy to implement and may be suitable for your case.
  • Mathematical methods, there are more that one, but take a look at Separating Axis Theorem. If your are only limited to rectangles (or/and circles and convex polygons), it will work best.

Solution 2:[2]

For anyone still having this issue:

You should look into the getTransform() and getInverseTransform() functions of sf::Transformable (https://www.sfmldev.org/documentation/2.5.1/classsf_1_1Transformable.php). Getting the inverse transforms of the player and a specific wall allows you to use a simple AABB collision algorithm (like SFML already implemented it in getGlobalBounds().intersects(...)). You basicly look at the local coordinate system of the player and how the wall is positioned to it, all translations, rotations and scaling ignored.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lorhan Sohaky
Solution 2 Ye.Feng