How do I make sure that I'm selecting the element which the mouse has clicked on?
Hopefully, this helps, this was done quickly, but I think you can figure it out from here I believe.
#include <iostream>
#include "SFML/Graphics.hpp"
#include <vector>
struct Shape
{
Shape(sf::Vector2f size) {
shape.setSize(size);
shape.setFillColor(sf::Color::Transparent);
shape.setOutlineThickness(1.f);
shape.setOutlineColor(sf::Color::Green);
}
sf::RectangleShape shape;
bool selected = false;
};
int main() {
sf::RenderWindow window(sf::VideoMode(1280, 800), "SFML Game");
srand((unsigned)time(nullptr));
sf::Event event;
bool mouseClicked = false;
bool mouseInsideRect = false;
bool dragging = false;
sf::Vector2f mouseRectOffset;
int mouseX = 0;
int mouseY = 0;
std::vector<Shape> shapeVec;
Shape* currentShape = nullptr; // keep track of current shape being moved
for (int i = 0; i < 10; ++i) {
auto shape = new Shape({ 64.f,64.f });
shape->shape.setPosition(rand() % 1100 + 100, rand() % 650 + 100);
shapeVec.push_back(*shape);
}
while (window.isOpen()) {
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed || event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape)
window.close();
if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Space) {
auto shape = new Shape({ 64.f,64.f });
shape->shape.setPosition(rand() % 1100 + 100, rand() % 650 + 100);
shapeVec.push_back(*shape);
}
}
// get the mouse position
auto mpos = window.mapPixelToCoords(sf::Mouse::getPosition(window));
// Moving the shapes
if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) {
if (mpos.x >= 0 && mpos.x < window.getSize().x && mpos.y >= 0 * mpos.y < window.getSize().y && !dragging) {
dragging = true;
for (auto& it : shapeVec) {
if (it.shape.getGlobalBounds().contains(mpos.x, mpos.y)) {
it.selected = true;
currentShape = ⁢
break;
}
}
}
}
else {
dragging = false;
if (currentShape)
currentShape->selected = false;
}
// removing the shapes
if (sf::Mouse::isButtonPressed(sf::Mouse::Right)) {
if (mpos.x >= 0 && mpos.x < window.getSize().x && mpos.y >= 0 * mpos.y < window.getSize().y) {
auto shapeIt = shapeVec.begin();
while (shapeIt != shapeVec.end()) {
auto it = *shapeIt;
if (it.shape.getGlobalBounds().contains(mpos.x, mpos.y)) {
shapeIt = shapeVec.erase(shapeIt);
}
else {
++shapeIt;
}
}
}
}
if (dragging == true) {
for (int i = 0; i < shapeVec.size(); i++) {
if(shapeVec[i].selected)
shapeVec[i].shape.setPosition(mpos.x,mpos.y);
}
}
window.clear();
for (int i = 0; i < shapeVec.size(); i++) {
window.draw(shapeVec[i].shape);
}
window.display();
}
return 0;
}