[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] frame independant movement



That approach is perfectly fine with linear movement - because the linear calculations aren't affected significantly by how large dt is (or put another way: x += vx*2 is nearly identical to x += vx*1, x += vx*1 on your computer)

However, with any nonlinear physics (like say, gravity's relationship to position, or an accelerating object)  or with discrete actions that happen once per frame (like say the artificial intelligence for an enemy that decides what to do once every frame), then your game behavior can change quite significantly depending on what values of dt you get.

---
For example, lets say you do gravity like this:
vy = vy + gravity*dt
y = y + vy*dt

with a dt of 2, from vy = 0, y = 0, the result is:
vy = vy + gravity*2 = gravity*2
y = y + (gravity*2)*2 = gravity*4

however if you get a dt of 1 twice, from the same starting point, the result is:
vy = vy + gravity*1 = gravity
y = y + (gravity)*1 = gravity
...
vy = vy + gravity*1 = gravity + gravity = gravity*2
y = y + (gravity*2)*1 = gravity + gravity*2 = gravity*3
---

so you've only moved 3/4 of the distance (3 vs. 4 gravitys) down with a frame rate that is twice as fast, even though you are parameterizing everything on dt. Note the acceleration component (which is linear with time) is consistent and accurate with both timestep sizes.

So you asked "what else do you need?" well the answer is if you want consistent non-linear physics (like say you want the players to jump the same all the time), then the "else" you need is fixed size timesteps for your physical simulation.


On Fri, Aug 27, 2010 at 8:27 AM, Christopher Night <cosmologicon@xxxxxxxxx> wrote:
Here's what I always do:

dt = clock.tick() * 0.001
x += vx * dt
y += vy * dt

And all the sprites have a think(dt) method that updates them as if dt seconds have passed. What else do you need?

-Christopher


On Fri, Aug 27, 2010 at 11:19 AM, James Paige <Bob@xxxxxxxxxxxxxxxxxxx> wrote:
On Fri, Aug 27, 2010 at 10:59:09AM -0400, Kris Schnee wrote:
> On 2010.8.27 10:36 AM, B W wrote:
>> Howdy,
>>
>> Reviving this old thread. The comments by Patrick and Brian really
>> intrigued me, so I pursued the topic. Found a few interesting articles
>> and one great article. My study has resulted in a recipe for those of us
>> continually nagged by the question, "how can I get constant game speed
>> independent of frame rate?". The demo requires Pygame, but the clock
>> module only requires Python.
>
> Isn't it simply a matter of creating a Pygame Clock object and calling
> clock.tick() to delay until the appropriate time to maintain some max
> framerate?

That only caps a max framerate. What Gumm is talking about is when your
framerate and your game simulation rate can be adjusted independantly

---
James Paige