Skip to main content
edited title
Link

Moving a Sprite using Mouse in SFML setOrigin(setOrigin logic needed)

Source Link

Moving a Sprite using SFML setOrigin logic

I trying to make a card game using SFML. I want to move the card relative to the position the player selects on the card. I managed to check if the card is pressed. However, when I click and drag, the top-left (the origin) of the card is immediately moved to where the mouse is. I tried to set the origin, in the process_events function, to 'event.mouseButton' (both x and y) each time the card is pressed but it moves to the top-left corner of the screen. I spent a lot of time on this. I hope you guys will help me out.

const int card_width = 79;
const int card_height = 123;

Game::Game()
: window(sf::VideoMode(1024, 800), "SFML")
, frame_rate(sf::seconds(1.f / 60.f))
, card(card_sheet, sf::IntRect(0, 0, card_width, card_height))
// 'card' is an sf::Sprite object pointing to an sf::Texture object that holds the sprite sheet. 
, selected(false)
{
    card.setPosition(500.f, 400.f);
    card.setOrigin(card_width / 2, card_height / 2);
    // I tried to set the origin to the center of the card.
    // Still doesn't look nice.
}

void Game::process_events()
{
    sf::Event event;
    while (window.pollEvent(event))
    {
        switch (event.type)
        {
            case sf::Event::Closed:
                window.close();
            break;
            case sf::Event::MouseButtonPressed:
                if (event.mouseButton.button == sf::Mouse::Left)
                    if (card.getGlobalBounds().
                                   contains(sf::Mouse::getPosition(window).x,
                                            sf::Mouse::getPosition(window).y))
                    {
                        // the problem is here
                        card.setOrigin(event.mouseButton.x, event.mouseButton.y);
                        selected = true;
                    }
                    
            break;
            case sf::Event::MouseMoved:

                if (selected)
                {
                    // stuff might need to be added here too
                    card.setPosition(sf::Mouse::getPosition(window).x, sf::Mouse::getPosition(window).y);
                }
            break;
            case sf::Event::MouseButtonReleased:
                selected = false;
            break;
            default: break;
        }
    }
}

void Game::update(sf::Time dt)
{
}

void Game::render()
{
    window.clear();
    window.draw(card);
    window.display();
}

void Game::run()
{
    sf::Clock clock;
    while(window.isOpen())
    {
        sf::Time dt = clock.restart();
        process_events();
        update(dt);
        render();
    }
}