[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [pygame] Smooth animation



On Tue, Dec 10, 2002 at 09:46:34AM +0100, azazel wrote:
> If I need to move my sprite slowly, for instance, I move it 1 pixel
> every frame update, and when I need to move it quickly instead 5
> pixels per frame update.

(snip)

> Is there a better way?

Here's how I did it, given my limited knowledge of the subject.

1. Each ship object has .vx and .vy members.  They're the velocity in
the x and y directions, respectively.  Each also has .x and .y, the
position.

2. When you call update(), pass in the return value of clock.tick(),
divided by 1000 (to return seconds instead of milliseconds).  update()
accepts that as 'timedelta'.

2a.  update() makes sure the velocity is accurate.  (In pySpaceWars,
this means it calculates the pull of gravity.)

2b.  update() then changes self.x and self.y:
        self.x += self.vx * timedelta
        self.y += self.vy * timedelta

2c.  update() then updates self.rect.x and self.rect.y accordingly.
We can't use self.rect.[xy] directly because they only hold integers,
and we need floating-point precision.


So, instead of jumping one or five pixels per frame, here's what you
do:

1. Figure out an ideal framerate.  In this case, it should be fairly
low.

2. Find out how many pixels per second correspond with 1 and 5 pixels
per frame, at that framerate.  Set these in variables somewhere.

3. Instead of telling the ship to move 1 or 5 pixel per frame, tell it to
move the corresponding number of pixels per second.

This way, if the game is running at the framerate you chose in step 1,
it's behaving the same way.  If the game is running faster, the
animation becomes smoother.  (Of course, if it's running slower, it'll
be even more coarse, but that's why I said to pick a low framerate.)

I'm not saying my way is better, but it worked for me.  YMMV and all
that crap.

-- 
Benjamin Geiger <benjamin.geiger@ptk.org>
PGP/GPG Key: 0x7F4E4038 (DSA/ElGamal 4096 bit) (NOYFB,P)
Please do not send me Microsoft Word files.

Attachment: pgp00000.pgp
Description: PGP signature