2
\$\begingroup\$

I'm relatively new to programming and I am attempting to write a 2d platformer in C++ using the SFML library.

The structure of my code is that I have a Stage class which contains a vector of sf::RectangleShape 's (the stage platforms). I have a method in the stage class to check for the collision between a player's hitbox and the stage as follows:

bool Stage::checkForStageCollisions(sf::RectangleShape player)
{
    for (unsigned int i = 0; i < collidableObjects.size(); i++)
    {
        if (player.getGlobalBounds().intersects(collidableObjects[i].getGlobalBounds()))
        {
            return true;
        }
    }
    return false;
}

Then in my player class I can perform logic based on whether there was a collision. The problem is that I need to know which object the player collided with to move them to the appropriate spot. Am i going about this the wrong way? Any help would be appreciated. Thank you!

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

You are totally on target. One approach would be to return an integer which is the index of which one you hit, and a "special value" if nothing was hit. So:

int Stage::checkForStageCollisions(sf::RectangleShape player)
{
    ...
            return i;
    ...
    return -1;
}

Elsewhere you could say, if(checkResult >= 0) [something was hit]. Or do something with the checkResult which is the index of the rectangle that was hit.

If there's several rectangles per "thing you might hit" you'll need more lists or something to convert from that index to the value you actually care about.

Hope that helps.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .