0
votes

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.

2

2 Answers

1
votes

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

0
votes

You have to forward declare your classes in order to make each other see each other.

carsprite.h

class FrogSprite; //declare your FrogSprite here

class CarSprite
{

};

frogsprite.h

class CarSprite;

class FrogSprite
{

};

after that, you can include the header files in its cpp files to see the classes's full definition.

carsprite.cpp

#include "frogsprite.h"

frogsprite.cpp

#include "carsprite.ccp"