Hi, I am new to SFML and C++ in general.
I am building the Conway's Game of life for a school project.
As base objects for my grid, I have Squares (which are sf::RectangleShape as for base).
The grid is a std::vector<std::vector<Square>> (vector of vectors of Squares).
What I am trying to do at the moment is to change the color of a square when I hover over it with the cursor.
My way of doing it (see code below):
1- I get the position of cursor when I move it
2- I iterate through my matrix and check for each square if it contains the position of the cursor (with .getGlobalBounds().contains(cursorPos))
But this does not work. It iterates but it does not find any collision.
Can you see what is wrong?
Thanks.
int main()
{
int width;
int height;
int numberSquareWidth = 15;
int numberSquareHeight = 15;
int squareSize = 20;
int offset = 1;
initializeWindowGridValues(width, height, numberSquareWidth, numberSquareHeight, squareSize, offset);
sf::RenderWindow window(sf::VideoMode(width, height), "Stephan's Game Of Life!");
std::vector<std::vector<Square>> matrix(numberSquareWidth, std::vector<Square>(numberSquareHeight));
initiatlizeGrid(numberSquareWidth, numberSquareHeight, squareSize, offset, matrix);
while (window.isOpen())
{
sf::Event event;
sf::Vector2i cursorPos;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
if (event.type == sf::Event::MouseMoved)
{
cursorPos = sf::Mouse::getPosition(window);
std::cout << "Position of cursor: " << cursorPos.x << "," << cursorPos.y << std::endl;
}
mouseHover(event, matrix, cursorPos);
}
window.clear(sf::Color::Black);
drawGrid(window, matrix);
window.display();
}
return 0;
}
void mouseHover(sf::Event &event, std::vector<std::vector<Square>> &matrix, const sf::Vector2i cursorPos)
{
for (auto &vector : matrix)
{
for (auto &square : vector)
{
if (square.getGlobalBounds().contains(static_cast<sf::Vector2f>(cursorPos))) //does square contain position of cursor?
{
std::cout << "Collision" << static_cast<sf::Vector2f>(cursorPos).x <<"," << static_cast<sf::Vector2f>(cursorPos).y << std::endl;
//square.setFillColor(sf::Color::Yellow);
}
}
}
}