Hi. Looking to be able to drag and drop shapes from a vector, but I'm finding that when dragging one of the shapes I instead drag all of the shapes from the vector to the mouse position instead of just the single shape. Was wondering how I can drag the one shape without affecting the others?
#include <iostream>
#include "SFML/Graphics.hpp"
#include "Shape.h"
#include <vector>
int main()
{
sf::RenderWindow window(sf::VideoMode(1280, 800), "SFML Game");
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;
while (window.isOpen())
{
while (window.pollEvent(event))
{
if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Space)
{
Shape shape(window.getSize());
shapeVec.push_back(shape);
}
if (event.type == sf::Event::MouseButtonPressed && event.mouseButton.button == sf::Mouse::Left)
{
mouseClicked = true;
for (int i = 0; i < shapeVec.size(); i++)
{
dragging = true;
mouseRectOffset.x = event.mouseButton.x - shapeVec[i].GetShape().getGlobalBounds().left - shapeVec[i].GetShape().getOrigin().x;
mouseRectOffset.y = event.mouseButton.x - shapeVec[i].GetShape().getGlobalBounds().top - shapeVec[i].GetShape().getOrigin().y;
}
}
if (event.type == sf::Event::MouseButtonReleased && event.mouseButton.button == sf::Mouse::Left)
{
mouseClicked = false;
dragging = false;
}
if (event.type == sf::Event::MouseMoved)
{
mouseX = event.mouseMove.x;
mouseY = event.mouseMove.y;
}
}
if (dragging == true)
{
for (int i = 0; i < shapeVec.size(); i++)
{
shapeVec[i].SetPos(mouseX - mouseRectOffset.x, mouseY - mouseRectOffset.y);
}
}
window.clear();
for (int i = 0; i < shapeVec.size(); i++)
{
shapeVec[i].Draw(window);
}
window.display();
}
return 0;
}