开发者

SDL_GetTicks()-based movement?

开发者 https://www.devze.com 2023-04-12 10:22 出处:网络
I\'m writing a game of pong in OpenGL and SDL. I have a small knowledge of how SDL_GetTicks() works but I am struggling to think of a way to implement how to make my ball move for example every 1000 m

I'm writing a game of pong in OpenGL and SDL. I have a small knowledge of how SDL_GetTicks() works but I am struggling to think of a way to implement how to make my ball move for example every 1000 milliseconds being the novice I am.

Short examples, explanations, help, anything at all would be appreciated greatly开发者_开发百科.


I solved it by creating my own Timer class. Technically, what you do is that at constructor you assign a start miliseconds value by using GetTicks()

Timer::Timer(uint32_t ToWait, void (*call_back)(void*), void* context) : Callback(call_back), Context(context), Running(true), ToWait_private(ToWait)
{
    StartTicks = SDL_GetTicks();
}

Now you implement an update() function, in wich you save current ticks every time

void Timer::Update()
{
    if(!Running)
        return;

    CurrentTicks = SDL_GetTicks(); //get the current ticks

    if(CurrentTicks - ToWait > StartTicks) //if the ticks are more than how much to wait
    {
        Running = false;

        Callback(Context); //call my callback or whatever
    }
}

This is not all code but it should give you a point like how to implement it. Since the SDL_ticks are counting miliseconds, you can also implement some convert function for setting time in seconds or so.

In your game mechanism, whenewer you need to wait, create an instance. Then, call Update() of timer. Good thing is that it does not have to be called regularily, as SDL_getTicks does give you the value every time.

The thing is to set a callback to a function, depends whether it is member function, then you should use some wrapper. In case of static function, there is nothing to fear and just use classic pointer to function. Lambda and many other things, stoppin, pausding timer can also be implemented, just be creative :]

To finally answer your question on HOW to make the ball move, you can call some

Move()

function as callback every single time the time is up. When moving the ball, you should, however, restart the timer. :]


Ye Olde Fix Your Timestep!

You don't have to use RK4, the "interpolate between the last two sim states" is the important part.

0

精彩评论

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

关注公众号