0
\$\begingroup\$

I'm trying to find free space to place rectangles, but even though I check for a collision using .intersects() it still places them through each other and somehow doesn't see the intersection happening while it's blatantly there.

This is my code at the moment:

#include "dungeonGenerator.h"

std::map<int, dungeonGenerator::dungeon_room> dungeonGenerator::newDungeon(int x, int y, int n)
{
    srand(time(NULL));
    std::map<int, dungeon_room> rooms;
    bool canPlace;

    for (auto i = 0; i < n; ++i)
    {
        canPlace = false;
        dungeon_room dungeon_room;
        while (!canPlace)
        {
            int height = rand() % x;
            int width = rand() % y;

            int pos_x = rand() % 512;
            int pos_y = rand() % 512;

            sf::RectangleShape room;
            room.setSize(sf::Vector2<float>(height, width));
            room.setFillColor(sf::Color(rand() % 255, rand() % 255, rand() % 255));
            room.setPosition(sf::Vector2<float>(pos_x, pos_y));
            dungeon_room.image = room;
            dungeon_room.collider = sf::IntRect(pos_x, pos_y, width, height);

            if (!rooms.empty())
            {
                auto i = 0;
                for (auto& room : rooms)
                {
                    std::cout << ++i;
                    canPlace = canPlaceRoom(&dungeon_room, &room.second);

                    if (canPlace == false)
                    {               
                        break;
                    }
                }
            } else
            {
                canPlace = true;
            }
        }
        rooms[i] = dungeon_room;
    }
    return rooms;
}

bool dungeonGenerator::canPlaceRoom(dungeon_room* room, dungeon_room* target)
{
    if (room->collider.intersects(target->collider))
    {
        return false;
    }
    return true;
}
\$\endgroup\$
0
\$\begingroup\$

Your collider uses a different width and height than your sf::RectangleShape: at line 22, you swapped width and height.

\$\endgroup\$

You must log in to answer this question.

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