| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- .. include:: ../_header.rst
- Prefab code generation
- ~~~~~~~~~~~~~~~~~~~~~~
- A prefab_ file is a scene and is compiled into JavaScript (or TypeScript) code. A regular scene file is compiled into a class that extends the `Phaser.Scene <https://photonstorm.github.io/phaser3-docs/Phaser.Scene.html>`_ class. It is a scene after all. However, the prefab_ file is compiled into a custom object class.
- The prefab_ class generated by the |SceneCompiler|_ extends a game object class, like an `Image <image-object.html>`_, a `BitmapText <bitmap-text-object.html>`_, etc... or `another prefab class <prefab-variant.html>`_.
- This is the code generated after compile the **Dragon** prefab:
- .. code::
- class Dragon extends Phaser.GameObjects.Image {
-
- constructor(scene, x, y, texture, frame) {
- super(scene, x ?? 100, y ?? 100, texture || "dragon", frame ?? "dragon/flamming_00");
- this.scaleX = 0.7;
- this.scaleY = 0.7;
- }
- }
-
-
- Note the prefab_ class extends the `Phaser.GameObjects.Image <https://photonstorm.github.io/phaser3-docs/Phaser.GameObjects.Image.html>`_ class, because the `prefab object <prefab-object.html>`_ is an `Image`_.
- The constructor of the **Dragon** class has the same arguments of the `Image`_ class, but by default, it uses the texture set in the `prefab object`_. Also, in the body of the constructor, are set the properties modified in the `prefab object`_:
- .. code::
- this.scaleX = 0.7;
- this.scaleY = 0.7;
- When the |SceneCompiler|_ compiles a regular scene file, the |PrefabInstances|_ in it are generated as instances of the prefab_ class:
- .. code::
- class Level extends Phaser.Scene {
-
- constructor() {
- super("Level");
- }
-
- create() {
- ...
- // create the instance of the Dragon prefab class
- const dragon = new Dragon(this, 190, 120);
- // add the instance to the display list
- this.add.existing(dragon);
- // modify the 'angle' property of the instance
- dragon.angle = -30;
- ...
- }
- }
- Also, the prefab_ class can be instantiated manually by you, at any time in your game. It is just a custom object class that looks like if you write it by hand.
|