So assuming that I have a sprite sheet loaded, or created and cached into the phaser cache. Creating a sprite that will make use of the animations in the sheet is a fairly straight forward process. I of course give the name of the sheet when making the sprite for starters. Then once I have a sprite, with a sprite sheet associated with it sprite I can then add an animation with the app method of the animation property of the sprite which is a reference to its animation manager.
something like this
This animation would be and animation called ‘walk’ that would consist of the first three frames of the sprite sheet associated with this sprite, will be played back as 12 frames per second, and will loop over and over again until the animation changes to something else.
I can then use the animation later in the state by grabbing a reference to the sprite, and calling the proper animation.
However to cover a full working example of this I am going to need to load, or create from code a sprite sheet, so lets take a look as an actual example of this in action.
In order to have an phaser animation example I first need a sprite sheet to work with. So for this example I will be using a solution I worked out that allows be to create sprite sheets with the 2d canvas drawing api. This sheet will contain two animations for a sprite. One that will be an animation that is to be played when the sprite is not moving, and another that is to be played when it is moving.
First off there is my sheetFromCanvas method that I can use to make a sprite sheet. This works by passing an object to it that contains, among other properties, an array of objects that declare the number of frames, and a method that will be used to render each frame for that animation.
This method allows me to make a sprite sheet with code, rather than loading an external sprite sheet. In any case animation is a time consuming aspect of game development, I often pursue making an animation with some kind of code solution rather than hand drawing the cells. If you all ready have a sprite sheet available in you project then you can skip this.
If you would like to learn more about making sprite sheets with this kind of solution I have written a post on making a spritesheet with canvas, in which I get into this method in detail. I will show an example of this being used in the next section when I make my state object for this example.
So now that I have my method that I can use to make a sprite sheet I will now show an example of this in action. I call the method in the create method of a state object to create the sheet, and add it into the state. In a simple example like the one I will show here this will all be done in a single state object, but in a more complex project this is something that might be done during another state in the project.