Sunday, 23 December 2012

Bouncy Text and Christmas Trees

First a quick video of the demo!

Code is available here.

The code runs much smoother than on YouTube :-) Hopefully each post in future will come with a video. The defaults are for the demo to run at 320 by 240 but you can adjust these values via the WinWidth and WinHeight Variables.

So how do we make the text bounce like this? Well, do you remember the Sin wave from trigonometry? Watch the 'M' in the video climb up to the top, back to the middle and then the bottom of the window and back up. We use a little bit of math to store the coordinates of this path in a list and each time we draw the window we move onto the next set of coordinates thus moving the text along the path. When it's gone through the list it goes back to the start so our animation loops.

The background Christmas trees dimensions are worked out and stored in treewidth and treeheight. We then have a couple of loops so we have 4 columns of trees over 3 rows. To liven things up the c3B data item adjust the shade of green. Can you figure out how to add more (smaller) trees to the scene?

The rest of the program covers the usual plumbing. An update function moves the text to the next set of coordinates in the list and it is called on a schedule. There is the on_draw handler for the window that actually takes care of the drawing.

One last point to mention is that we want the text to appear in front of the trees. Pyglet has the concept of groups. Have a look at the objects foreground and background. By setting up our objects in the right group we can ensure Pyglet draws them in the desired order.

Hope to return with something 3D next time around. Happy Python/Pyglet-ing!!

No comments:

Post a Comment