Animation Tutorial 00
2009-11-24 Robert-Reinder Nederhoed (Please post suggestions and questions about this tutorial.)
Getting started
You need:
- the python programming language
- cocos2d
- pyglet
- 4 images for an animation
You can copy and paste from this page, or get the code and images from Launchpad:
python code:
tutorials/animation-00/animate.py all tutorial content:
http://bazaar.launchpad.net/~nederhoed/monkeyjungle/trunk/files/head%3A/tutorials/animation-00/The basis for your simple animation is the following code:
from cocos.layer import Layer
from cocos.scene import Scene
from cocos.sprite import Sprite
from cocos.director import director
import pyglet
# Your artwork
FLAPPING = ['parrot-009.png',
'parrot-010.png',
'parrot-011.png',
'parrot-010.png']
director.init(width=320, height=240)
context = Layer()
parrot = TODO # to be replaced
context.add(parrot, name="still")
director.run(Scene(context))Your first Sprite
To create a non-animated Sprite you would do something like this:
parrot = Sprite(FLAPPING[0], position=(200, 50), scale=0.5)With this line you instantiate a Sprite with the first image from the
FLAPPING list.
Sprite.__init__ accepts an image filename or a loaded image. The following lines work just the same, but use less cocos2d functionality:
image = pyglet.image.load(FLAPPING[0])
parrot = Sprite(image, position=(200, 50), scale=0.5)On to Animation
The cocos2d Sprite not only accepts a pyglet Image instance for its visualization. It also accepts a
pyglet Animation.
You can create a pyglet Animation by adding pyglet AnimationFrame instances. This sounds complicated, right? Well, I agree.
So let's take a shortcut.
The Animation class has a
factory method you can use to create an Animation from a series of images.
From the pyglet API documentation:
Animation.from_image_sequence(cls,
sequence,
period,
loop=True)
Create an animation from a list of images and a constant framerate.
We'll do just that:
# Create the list of pyglet Images
images = (pyglet.image.load(filename) for filename in FLAPPING)
# 5 frames per second implies 0.2 sec per image
animation = pyglet.image.Animation.from_image_sequence(images, 0.2)
parrot = Sprite(animation, position=(200, 50), scale=0.5)There you go! A parrot flapping at 5 frames per second. With 4 images, this parrot has a flap speed of 1.25 per second.
Next steps...
This should have got you started with animated sprite characters. Now it's up to you to use your animated characters in a game.
I'm working on an example with 2 animations for 1 character: flapping when flying, sitting still when in a tree. Once I have my code ready, I will add a page here.
Please
post suggestions and questions about this tutorial. Thanks!