Search code examples
c++sfml

finding mouse click in rectangle's vector using sfml


We just learnt SFML by our own and we are trying to realize a function that is finding a mouse click location and finds it in a rectangle's vector. We are trying to color the outline of the specific rectangle that we're clicking on... This is what we tried to write:

void Controller::run_board(Board ourBoard)
{

    while (m_window.isOpen())
    {
        sf::Event e;

        while (m_window.waitEvent(e))
        {
            m_window.clear();
            drawboard(ourBoard);

            creatMenu(ourBoard);

            m_window.display();




            if (auto event = sf::Event{}; m_window.waitEvent(event))
            {
                switch (event.type)
                {
                case sf::Event::Closed:
                    m_window.close();
                    break;
                }

                if (event.type == sf::Event::MouseButtonPressed)
                {
                    sf::RectangleShape rec;
                    if (event.mouseButton.button == sf::Mouse::Left) {
                        auto xCoord = event.mouseButton.x;
                        std::cout << xCoord;
                        auto yCoord = event.mouseButton.y;
                        sf::Vector2f worldPos = m_window.mapPixelToCoords(yCoord);

                        rec.setPosition(xCoord, yCoord);
                        //m_window.clear();
                        for (int i = 0; i < m_length; i++)
                            for (int j; j < m_width; j++)
                            {
                                if (m_vecRec[i][j].getGlobalBounds(worldPos))
                                {
                                    m_vecRec[i][j].setOutlineColor(sf::Color::Red);
                                    m_window.draw(m_vecRec[i][j]);
                                }
                            }


                        //m_window.clear();

                        m_window.display();

                        //  m_recMenu.setFillColor(sf::Color::Red);
                            //rec.setPosition(c.x, c.y);

                    }
                }

            }

        }
    }
}

Solution

  • If m_vecRec[i][j] is a Shape or a Sprite, getGlobalBounds will return a bounding rectangle. You should be able to call .contains(worldPos) on that to see if the mouse position is within the shape's bounding box:

    if (m_vecRec[i][j].getGlobalBounds().contains(worldPos)) { ... }
    

    I suggest storing the pair i,j somewhere in your Controller so you can remember which rectangle was clicked last, and undo the coloring if necessary.