Skip to main content

Simplifying sprites and image sheets in Corona SDK

I like many things about Corona SDK, but one thing I don't like very much is the API provided for handling of image sheets and sprites. In my opinion it is difficult to use and very fragile because of poor encapsulation and coupling, including things like:

  • No common way to create images and sprites from the same image sheet. You're left using display.newImage(), display.newImageRect() and display.newSprite().
  • Selecting frame from an image sheet is done using frame number, for example display.newImage(sheet, 1). Not only does this expose implementation details, it also makes the code really hard to read since you don't know the meaning of the integer unless you examine the image sheet and actually count the frames. Imagine having a large image sheet with 20+ frames trying to figure out what image will be displayed by display.newImage(sheet, 13)... And if you ever want to change the frame order within the sheet, you must also change every call to display.newImage() and display.newImageRect() where the image sheet is referenced. Needless to say, this can be really painful.
  • Same thing with selecting a frame from a sprite sequence. This is also done using frame number. But this time there's a small distinction from the image case that makes a big difference. The frame number you specify is related to the frames of the sprite sequence rather than the actual image sheet. This is described better in this sprite tutorial by Corona Labs.
  • The error handling is poor. For example, the end result of an invalid image sheet or sprite sequence will often be just a nil object returned by one of the display.newX() functions, leading to tedious and frustrating debugging sessions. Another example is that specifying a frame number that is out of bounds for a given sprite sequence only yields a warning in the console log. I'd prefer to get an in-your-face error message instead, since this will always be a programming error that can easily be fixed.
To address these issues I have created a class called Spright which is basically just a factory class for images and sprites. It solves the issues mentioned above by wrapping up the image sheet together with its sprite sequences so you won't have to care about them anymore once your Spright objects have been set up. Sprites and images created by Spright are just normal Corona SDK objects, so once created you can use them just like normal sprites and images.  

The following image of a 6-sided die is used in my example to show how to create both static images and animated sprites using the same Spright object. Save it as die.png in the same folder as the example code.

Running the example in the simulator should look something like this, where the top three dice are static and the bottom three animated sprites using different sequences.


Comments