Welcome, Guest. Please login or register. Did you miss your activation email?

Show Posts

This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.


Messages - WellBob

Pages: [1]
1
General / Re: Drag and Drop from a Vector of Shapes
« on: August 25, 2020, 06:28:32 pm »
How do I make sure that I'm selecting the element which the mouse has clicked on?

2
General / Drag and Drop from a Vector of Shapes
« on: August 23, 2020, 05:35:11 pm »
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;
}
 

Pages: [1]
anything