SFML community forums

Help => Graphics => Topic started by: Jan666 on July 17, 2022, 12:17:10 pm

Title: Collision with multiple RectangleShapes
Post by: Jan666 on July 17, 2022, 12:17:10 pm
Hello, i have a question, i have made multiple RectangleShapes
with following code:
RectangleShape* wall = new RectangleShape;
FloatRect wallRect = wall->getGlobalBounds();

std::vector<RectangleShape> walls;
walls.push_back(*wall);

...

for(int i = 0; i < walls.size(); i++){
       
        walls[i].setPosition(Vector2f(300, 2000));
     
     walls[i].setSize(Vector2f(50, 300));
        walls[1].setPosition(Vector2f(300, 800));
        walls[1].setFillColor(Color::Blue);
        walls[1].setSize(Vector2f(500, 100));
        walls[2].setPosition(Vector2f(900, 500));
        walls[2].setFillColor(Color::Yellow);
        window.draw(walls[i]);

 

How i can do the collision detection, i have
a simple RectangleShape for the Player, it doesnt work when i give both a FloatRect + getGlobslsBounds and intersects them, someone know?

Title: Re: Collision with multiple RectangleShapes
Post by: Hapax on July 17, 2022, 04:31:19 pm
It's worth noting that "wallRect" will only give the global bounds of "wall", which is a newly constructed rectangle shape so will be all zeroes.

Anyway, to access the global bounds of each individual wall in the vector, simply access the individual wall element and get its global bounds, thus:
sf::FloatRect globalBoundsForThisCurrentWall = walls[i].getGlobalBounds();
where i is the wall you want the bounds for and "globalBoundsForThisCurrentWall" is the float rectangle representing the bounds.

Remember you need to update the float rectangle whenever it could have possibly changed, even if that means immediately before using it. i.e. getting the bounds again using the code above.


On a separate note, you can create a vector of walls without creating a temporary one first and even specify how many you want in it
std::vector<sf::RectangleShape> walls(10u); // create a vector of 10 walls

Also, for clarity, it's often better to separate updates with display so try setting up or updating the rectangles in a loop and then drawing them all with the rest of the draw calls.
Something like:
for (auto& wall : walls)
    window.draw();
will draw all of the walls.

You should also notice that you have set position, size and fill colour twice in your loop. You're also applying some of them directly to specific walls (1 and 2) instead of the one you're looping through...
Title: Re: Collision with multiple RectangleShapes
Post by: Jan666 on July 17, 2022, 07:44:49 pm
Thanks, this help me a lot