Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Rectangular Boundary Collision  (Read 2399 times)

0 Members and 1 Guest are viewing this topic.


  • Hero Member
  • *****
  • Posts: 3035
  • My number of posts is shown in hexadecimal.
    • View Profile
Rectangular Boundary Collision
« on: July 11, 2017, 08:08:46 pm »
Rectangular Boundary Collision

SFML's sprites and shapes can provide you with their axis-aligned boundary boxes (getGlobalBounds) and you can easily use these rectangles to test if they intersect. Unfortunately, this only allows axis-aligned collision detection.

Rectangular Boundary Collision allows testing collision based on their original rectangular boundary box (getLocalBounds). It tests to see if an object's rectangular boundary collides with another object's rectangular boundary. This method, however, allows transformations to be taken into account - most notably, rotation.

Rectangular Boundary Collision is a single, templated free-function contained within the "collision" namespace:
const bool spritesAreColliding = collision::areColliding(sprite1, sprite2);

You only need the header, which is approximately 100 lines of code...

The collision is performed in three stages:
  • Level 0 - AABB (axis-aligned boundaries boxes):
    tests the axis-aligned boundaries boxes (equivalent to getGlobalBounds) of the objects to see if they intersect.
  • Level 1 - Corner inside opposite object:
    tests to see if any of either object's corner is inside the other object.
  • Level 2 - SAT (Separating Axis Theorem):
    tests using a simplified version (for rectangles) of SAT to catch other cases.
If, at any time, the result is certain, the following stages are not calculated. This allows easier detections to be done without resorting to the more involved calculations.

The collision level represents after which stage to leave the function, regardless of if a result is certain.

(red = collision, green = no collision)

Wiki page:

GitHub repository (it's a part of SfmlSnippets):

Example used to create the above screenshots is included in the repository and also on the wiki page.
« Last Edit: June 08, 2019, 10:48:00 pm by Hapax »
Selba Ward - SFML drawables
Kairos - Timing Library
Rectangular Boundary Collision - Rectangular SAT Collision

@Hapaxiation - Hapaxia on Twitter