[英]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]
是一個Shape
或一個Sprite
, getGlobalBounds
將返回一個邊界矩形。 您應該能夠調用.contains(worldPos)
以查看鼠標位置是否在形狀的邊界框內:
if (m_vecRec[i][j].getGlobalBounds().contains(worldPos)) { ... }
我建議將i,j
對存儲在您的Controller
某個位置,以便您記住最后單擊哪個矩形,並在必要時撤消着色。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.