Animating several things at once

October 24, 2009
by Lee Spector (lspector)

Now that several of you are making animated characters I’ve received a lot of questions about how to make several characters move at the same time. There are several ways to approach this, but one of the simplest and most popular is to think in terms of complete frames. The idea is to break up the animation process as follows:

loop for each time step:
  erase the whole screen
  draw everything where it should be for this time step
  delay for a bit, to let the viewer see the current frame
  change the positions of everything for the next time step

This means you have to keep track of the positions of everything somewhere (maybe in global variables), that you have to rewrite your character-drawing code to draw a single instance of the character in a single position (which should be easy), and that you have to separate out the code for changing the position of your character from step to step.

That main loop, by the way could be an iterative loop (maybe created with “for” or “do” or “while“) or it could be implemented with a recursive call.

Note that this “erase the whole screen” idea doesn’t play very nicely with the idea of having all of our characters animate at the same time on the same screen in class. That’s okay for now, but with a little more effort you could change your system to do this:

erase the whole screen
loop for each time step:
  draw everything where it should be for this time step
  delay for a bit, to let the viewer see the current frame
  erase all of the individual characters, based on where things are this time step
  change the positions of everything for the next time step

If you do this then you could later change your calls to “ellipse,” “rectangle,” “line,” etc. to calls to “send-code” that tell the server to call ellipse, rectangle, line, etc. And since you’d only be erasing the place where your last drawing was made there wouldn’t be any conflicts except when things actually overlap.



Leave a Reply

You must be logged in to post a comment.