pythontimedelta2d-gamesgame-looparcade

How does delta_time work on python arcade?


I’m going through the tutorials on python arcade and would like to know how/why a function works.

There is a function named on_draw(delta_time)

I looked around the code for arcade but can’t figure out how the library knows to keep the clock running. Can someone please help me understand how and why it works?

One example is here: http://arcade.academy/examples/bouncing_rectangle.html#bouncing-rectangle


Solution

  • can’t figure out how the library knows to keep the clock running.

    The library uses a clock to call your on_draw function periodically, passing it the elapsed time in seconds as argument

    Now since you asked details on how is this all wired up, let's have a look:


    It all starts in your main() function. You're calling:

        # Tell the computer to call the draw command at the specified interval.
        arcade.schedule(on_draw, 1 / 80)
    

    So you're calling arcade.schedule passing a reference to on_draw.

    Fine, down the rabbit hole we go!


    arcade.schedule is documented here as follows:

    arcade.schedule(function_pointer: Callable, interval: numbers.Number)
    

    Schedule a function to be automatically called every interval seconds.

    ...it's a shame they are not a bit more specific about how the function is called (i.e. with what parameters, if any) -- we have to look at the source which is, docstring omitted:

    def schedule(function_pointer: Callable, interval: Number):
        pyglet.clock.schedule_interval(function_pointer, interval)
    

    That's it! It's basically delegating the job to pyglet.clock.schedule_interval, and here again, we don't know what params it passes to our function... I mean we kind of have an idea, but you asked for a proof, so a proof you will get!


    Dig up the docs for schedule_interval (edited for brevity and clarity -- bold text mine):

    schedule_interval(func, interval, *args, **kwargs)

    Schedule a function to be called every interval seconds.

    The function should have a prototype that includes dt as the first argument, which gives the elapsed time, in seconds, since the last time it was called. Any additional arguments given to this function are passed on to the callback:

    def callback(dt, *args, **kwargs):
      pass
    

    Parameters:

    • func (callable) – The function to call when the timer lapses.
    • interval (float) – The number of seconds to wait between each call.

    Here you have it: it says that your function will be called with the elapsed time as first argument. (well ok, I had to edit that part in, but I'm sure that's what they meant!)


    Now, please don't ask me how pyglet.clock works internally ;)