开发者

Sprite movement

I'm ripping my hair out over this one. For some odd reason I cannot find out / think 开发者_如何学Cof 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)


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);
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜