I'm messing around with Phaser 3 in an es6 syntax. In Phaser 3 everything is now composed of Scenes, where you load/update/etc everything. So, for the primary Game
scene, I extend Phaser.Scene
.
export default class Game extends Phaser.Scene {
preload()
create()
...
But let's say I have a player, which will involve 100's of lines of code that I would like to keep in a separate file for code cleanliness. How do I organize that?
Every tutorial/info I find about it just includes all of the code for the scene in the same file, but this is obviously not realistic for fully fleshed-out games. I want to separate many elements of the game into their respective classes/files.
So, I just create a player class, that doesn't extend anything? Or should I extend it by something like Phaser.Sprite
?
I think the reason most tutorials throw everything in one file is because:
To answer your specific question "So, I just create a player class, that doesn't extend anything? Or should I extend it by something like Phaser.Sprite
?", it depends.
I'm working in TypeScript, so my structure and code is a bit different, but I have a src directory structure like the following:
In the ts/Scenes directory I throw all of my scenes, that extend Phaser.Scene
. In the ts/Prefabs directory (prefabs is something I picked up years ago from a Phaser 2 tutorial) I put any custom classes.
Looking at the game I'm working on now, I have one that extends Phaser.GameObjects.Group
, three that extend off of that custom object, and then a couple that don't extend off of anything. In the past I've extended off of Phaser.Sprite
as well.
The real question of whether to extend off of Phaser.Sprite
or not is based upon what you want the object to do for you.
In my case I wanted to create a basic Character
class that my Hero
and Monster
instances could extend, and that would create sprites within the game when I created them. I opted for a Group
because the sprites I'm using consist of two parts, so with a Group I could add both Sprite
s to it when I created the object, but could have gone with a Sprite
had I just needed one asset.
One of my other custom objects just stores information about the game state, so since there's nothing that actually needs to display in game when it exists, it doesn't extend anything in Phaser.GameObjects
.
So the question for you is, when you create a new Player
, do you want it to display as a Sprite
with additional functionality/properties, or not? If the former, extend Sprite
(or whatever Phaser.GamesObjects
you need to. Otherwise don't.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With