Question

I'm ripping my hair out over this one. For some odd reason I cannot find out / think of how to move a sprite in SFML and or SDL. The tutorials I've looked at for both libraries state nothing about this; so I assume that it's more of a C++ thing than a library thing.

So I was wondering; how do you move a sprite?

(When I say move, I mean have the sprite "glide" across the window at a set speed)

Was it helpful?

Solution

You need a loop that gets called a fixed number of times per second, then you update the x,y values of the sprite each frame.

For SFML you have sprite.move

while (App.IsOpened())
{
    // Process events
    sf::Event Event;
    while (App.GetEvent(Event))
    {
        if (Event.Type == sf::Event::Closed)
            App.Close();
    }

    // Get elapsed time
    float ElapsedTime = App.GetFrameTime();

    // Move the sprite
    if (App.GetInput().IsKeyDown(sf::Key::Left))  Sprite.Move(-100 * ElapsedTime, 0);
    if (App.GetInput().IsKeyDown(sf::Key::Right)) Sprite.Move( 100 * ElapsedTime, 0);
    if (App.GetInput().IsKeyDown(sf::Key::Up))    Sprite.Move(0, -100 * ElapsedTime);
    if (App.GetInput().IsKeyDown(sf::Key::Down))  Sprite.Move(0,  100 * ElapsedTime);
}

OTHER TIPS

My favorite way to do this is to set up a recurring timer using SDL_AddTimer with a callback function that posts a custom event into the event queue every 20 milliseconds. Whenever your event loop comes across this event, update the sprite position and redraw that section of the screen (draw background over where the sprite was and draw the sprite in its new location).

The nice thing about doing it this way is that even if you temporarily fall behind on updating the screen, the internal representation of the sprite will still flow regularly. This is important if you are doing any collision detection, where having the sprite suddenly jump halfway across the screen could let it pass through a wall that was supposed to block it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top