Reputation: 37
I'am looking for a way to make multiple clickable rectangle shapes appear on the users screen using SFML. The code that i wrote only works for the last initialized shape and changes the color for all of the squares.
#include <SFML/Graphics.hpp>
#include <iostream>
using namespace std;
int main()
{
sf::RenderWindow window(sf::VideoMode(1280, 720), "warships");
sf::RectangleShape shape(sf::Vector2f(50, 50));
shape.setFillColor(sf::Color::Green);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
window.clear(sf::Color::Black);
for (int i = 0; i < 10; ++i)
{
for (int j = 0; j < 10; ++j)
{
int x,y;
y = 50 + 65 * i;
x = 260 + 80 * j;
shape.setPosition(x,y);
window.draw(shape);
}
}
if (shape.getGlobalBounds().contains(window.mapPixelToCoords(sf::Mouse::getPosition(window))) and event.type == sf::Event::MouseButtonPressed )
shape.setFillColor(sf::Color::Yellow);
window.display();
}
return 0;
}
Upvotes: 2
Views: 550
Reputation: 289
As suggested in the comments, you create only one RectangleShape and then change it's position. Probably better idea would be to create array of shapes with predefined positions at the begining of your code like this:
std::vector<sf::RectangleShape> shapes;
for (int i = 0; i < 10; ++i)
{
for (int j = 0; j < 10; ++j)
{
int x,y;
y = 50 + 65 * i;
x = 260 + 80 * j;
shapes.push_back(sf::RectangleShape(sf::Vector(x, y)));
shapes.back().setFillColor(sf::Color::Green);
}
}
then in your drawing loop just simply
window.clear(sf::Color::Black);
for (auto& shape : shapes)
{
if (shape.getGlobalBounds().contains(window.mapPixelToCoords(sf::Mouse::getPosition(window))) and event.type == sf::Event::MouseButtonPressed )
shape.setFillColor(sf::Color::Yellow);
window.draw(shape);
}
window.display();
Upvotes: 2