Tell me more ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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))
            App.Close();

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

        // Clear screen
        App.Clear();

        // Draw the sprite
        App.Draw(Sprite);

        // Update the window
        App.Display();
    }

    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

1 Answer

up vote 2 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

 
discard

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.