This is a post on using the Sprite.data object for appending properties, and methods to a single Sprite object that are project specific in phaser ce. In this post I am using Sprites, and a solution for making a sprite sheet from canvas, as well as many other phaser ce related topics.As such this is not a getting started post on phaser ce, but just a post on one little topic when it comes to phaser ce game development.
For a basic example of using the Sprite.data object I made a simple example that just involves moving a sprite back and forth on the screen using some properties and methods appending to the Sprite.data object.
So for this very simple getting started example I made a helper in which I pass a reference to a Phaser.Game instance, and a sprite that I have made before hand, and the helper appends some values, and a method that can be used to accomplish the simple back and forth movement.
When I put together a state object that will make use of this helper I use this method to setup the sprites data object in the create method of the state object, and then call the step method in the update method of the state object.
For very basic examples like this I just use some very simple solid color box sprite sheet, so a canvas solution like this will work fine.
This kind of solution can also work for making sprite sheets that are a little more involved as well, for more on that topic you might want to check out my post on making sprite sheets with canvas.
So now it is time to tie everything together with a Phaser.Game instance and just a single state object for now. After setting up my Phaser.Game instance I create a single state object that I will call ‘basic’ and in the create method of this basic state I create my sprite sheet with the canvas solution helper described above. After I have my sprite sheet in the cache, I use it to create and skin a new sprite, and give it a name. I then of course use my setupDataObject method to append what I need to the sprites data object my passing the Phaser.Game instance and a reference to the sprite as well. Then in the update method of the basic state I call my step method that is attached to Sprite.data to step the movement of the sprite.
When this example is up and running the box move back and forth as expected, using properties and a method that are tucked away into its data object.
So the Sprite.data object is the phaser ce standard way of assigning any kind of properties or methods that should be attached to a sprite insistence. One way or another there is often a need to do something like this for just about any phaser ce project, so I might as well stick to the common standard way of doing it via Sprite.data.