Search code examples
c++classcollisionsfmldetection

C++ SFML collision detection between different classes


I am making a C++ SFML version of Frogger and currently trying to implement collision detection between the frog and other objects (cars, trucks, logs etc). I have separate classes for the frog and the game objects and want to use bounding boxes to detect intersections as shown below.

// get the bounding box of the entity
sf::FloatRect boundingBox = entity.getGlobalBounds();
// check collision with another box (like the bounding box of another 
entity)
sf::FloatRect otherBox = ...;
if (boundingBox.intersects(otherBox))
{
    // collision!
} 

The problem I am having is that I have no idea how to make this work with two sprites from separate classes and after days of searching I can't find an explanation of how to do it.


Solution

  • Suppose there are two objects 'a' and 'b' that contain the sprites that you want to test for. Then you can call the following in your code to test for a collision between them:

    #include "MyEntityA.hpp"
    #include "MyEntityB.hpp"
    
    MyEntityA entity_a;
    MyEntityB entity_b;   
    
    if(entity_a.getSprite().getGlobalBounds().intersects(entity_b.getSprite().getGlobalBounds()))
    {
        // A collision happened.
    }
    

    Look here for further information: https://www.sfml-dev.org/tutorials/2.1/graphics-transform.php#bounding-boxes