As you can see, the spritesheet has our SS Goku facing down, left, right and then up. We now can replace our old single sprite, with this new four paneled sheet. Head on over to our
preload() function and remove the line that loaded our single image sprite and replace it with the following:
Notice: We changed our sprite variable name to reflect the change and be a little more descriptive (
goku-4-panel). The image path changed, but the big variable that could be different to your needs are the following three arguments passed. The third and fourth arguments are the height and width of a single block within our sprite sheet, and the fifth argument is how many panels are in our spritesheet. Okay cool!
Now let’s head over to the
create() function and update our sprite definition here. Remove the old definition and add the following 2 lines:
We now have a new sprite! But what is that second line?!
sprite.animations.frame = 0; This tells the initial state of our spritesheet, which block to use. If you have questions on which number to place here, take a look at the breakdown below. Keep in mind, the render always starts from top left, move right then to the next row, left to right again.
We are so close to being done, we have to do one more thing… accounting for user interaction and updating our sprite to reflect that interaction. Let’s head on over to the
update() function. Our
if statement should now look like this:
What did you notice that changed?! Yep, the
sprite.animations.frame references. This is mapping the new frame depending on which direction we are going! Perfect, now we have a character that faces the direction it is moving, done.
Up next… a sprite debugging helper.
If you would like the source files for this tutorial: Download source files