使用 sfml 在矩形的向量中找到鼠标单击

finding mouse click in rectangle's vector using sfml

我们刚刚自学了SFML,正在尝试实现一个寻找鼠标点击位置的功能,并在一个矩形的向量中找到它。我们正在尝试为我们单击的特定矩形的轮廓着色...这就是我们尝试编写的内容:

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);

                    }
                }

            }

        }
    }
}

如果 m_vecRec[i][j]ShapeSpritegetGlobalBoundsreturn 一个边界矩形.您应该可以调用 .contains(worldPos) 来查看鼠标位置是否在形状的边界框内:

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

我建议将 i,j 对存储在 Controller 中的某处,这样您就可以记住最后单击的矩形,并在必要时撤消着色。