Augmenting phaser

Augmenting phaser

When I made Monstro in the first place I used Starling as the rendering framework but because I’ve earlier worked by directly modifying BitmapData I had my own set of Display Objects and their properties. One of the properties I needed in Starling was “center” which retrieves the center position of a sprite and sets it, a thing that can be easily replaced by x = value - width / 2 but the resulting code is not as clear and is much more prone to a mean typo.

Since for Starling I just made my own fork I didn’t really have a problem there, but for Phaser I decided to stick to the main repository to avoid the pain of having to keep it up to date and eventually growing in a completely different direction and being 500% unhappy.

So the solution I have figured out was to utilize the fact that JavaScript is prototype-based language and decided to augment the existing Phaser classes with properties of my own. Gist with all the changes I’ve made.

It includes such augmentations:

  1. Methods positionCenter/positionMiddle – This function positions the object exactly in the horizontal center/vertical middle of the screen (it takes the first Phaser.Game object to get the screen dimensions).
  2. Methods positionCenterParent/positionMiddleParent – Like the above but it uses the parent of the object instead of the whole screen.
  3. Properties right/bottom – Get/set the position of the right/bottom edge of the object.
  4. Properties center/middle – Get/set the position of the center/middle of the object.
  5. Methods globalToLocalX/globalToLocalY – Given the global position X/Y it returns the said position relative to the object’s local space.

If, like me, you’re a TypeScript user, the Gist also includes a definition file with references to the augmentation files. Just make sure to reference it in your bootstrap or whatever after you reference Phaser. Unfortunately th version of TypeScript I am using does not allow you to define the same class in multiple places, so I had to modify my phaser.d.ts file manually to add the augmentations.

[mc4wp_form id="444"]