Creating animations in PlayMyCode

Here's a short example on how to create animations for use on PlayMyCode.

In this example, the animation is made up from one spritestrip - a single image containing all of the frames that make the animation.


There's our little pink devil!  There are four frames in total with each frame having a size of 60pixels by 60pixels.

To get this little fellow to animate, I created a very simple class called Animation().  You can find this class in the source code of the example below (just click on the Play My Code button)



First, we load our spritestrip image:

    $devilImage = new Image("Devil2_spr_strip4.png")


And then, create the animation:

    animation  = new Animation($devilImage, 4, 0, -1, 60, 60, 100, -1)



Ok, so what do all those numbers mean?  As mentioned previously, this animation has 4 frames. Each frame is 60x60 pixels in size and we want to animate with a 100ms delay between frames. We also want it to loop forever.

So:
    $devilImage   - the image containing the animated frames
    4             - the number of frames
    0             - the starting frame
    -1            - the end frame (we give -1 here so that it uses all frames
    60            - each frame is 60 pixels wide
    60            - each frame is 60 pixels high
    100           - the delay (in milliseconds) between each frame
    -1            - loop the animation forever


All that's left is to update and draw the animation.  Both of these operations are done within the main game loop (onEachFrame):

    animation.update(delta)
    animation.draw(100, 100, true)


The animation.update(delta) will automatically manage all of the image manipulation for you.

Take a look through the Animation() class as there's a few other methods that allow greater flexibility, such as drawing a scaled/rotated image, stopping/restarting the animation etc.

The animation class doesn't take a copy of the source image so it's fairly memory efficient.  Just declare your images as globals first.

Any questions, then feel free to ask :)

Popular Posts