Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to be able to move a sprite from a current location to another based upon where the user clicks in the window. This is the code that I have:

#include <SFML/Graphics.hpp>

int main()
    // Create the main window
    sf::RenderWindow App(sf::VideoMode(800, 600), "SFML window");

    // Load a sprite to display
    sf::Texture Image;
    if (!Image.LoadFromFile("cb.bmp"))
        return EXIT_FAILURE;
    sf::Sprite Sprite(Image);

    // Define the spead of the sprite
    float spriteSpeed = 200.f;

    // Start the game loop
    while (App.IsOpened())
        if (sf::Keyboard::IsKeyPressed(sf::Keyboard::Escape))

        if (sf::Mouse::IsButtonPressed(sf::Mouse::Right)) {
            Sprite.SetPosition(sf::Mouse::GetPosition(App).x, sf::Mouse::GetPosition(App).y);

        // Clear screen

        // Draw the sprite

        // Update the window

    return EXIT_SUCCESS;

But instead of just setting the position I want to use Sprite.Move() and gradually move the sprite from one position to another. The question is how? Later I plan on adding a node system into each map so I can use Dijkstra's algorithm, but I'll still need this for moving between nodes.

share|improve this question
up vote 3 down vote accepted

The easiest way I see is to store velocity, when user clicks on screen. This velocity will define, which direction sprite should move and by what speed (so for example direction * spriteSpeed).

Direction can be obtained by simple vector math: (TargetPosition - CurrentPosition).normalize()

And then you will update sprites position each frame. So just add to while loop: CurrentPosition += Velocity * ElapsedTimeSinceLastFrame. ElapsedTimeSinceLastFrame is just for sure - if you don't use time and run this application on faster machine (while loop will be executed faster), your sprite will move of course faster.

And finally - you should control, if sprite is at the end of its journey. So control, if (Velocity * ElapsedTime).length() is not more than (TargetPos - CurrentPos).length(). If it is, move sprite to target position and set velocity to zero (or set some flag not to update sprite position till next mouse click).

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.