prefab-code.rst 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. .. include:: ../_header.rst
  2. Prefab code generation
  3. ~~~~~~~~~~~~~~~~~~~~~~
  4. 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.
  5. 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>`_.
  6. This is the code generated after compile the **Dragon** prefab:
  7. .. code::
  8. class Dragon extends Phaser.GameObjects.Image {
  9. constructor(scene, x, y, texture, frame) {
  10. super(scene, x ?? 100, y ?? 100, texture || "dragon", frame ?? "dragon/flamming_00");
  11. this.scaleX = 0.7;
  12. this.scaleY = 0.7;
  13. }
  14. }
  15. 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`_.
  16. 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`_:
  17. .. code::
  18. this.scaleX = 0.7;
  19. this.scaleY = 0.7;
  20. When the |SceneCompiler|_ compiles a regular scene file, the |PrefabInstances|_ in it are generated as instances of the prefab_ class:
  21. .. code::
  22. class Level extends Phaser.Scene {
  23. constructor() {
  24. super("Level");
  25. }
  26. create() {
  27. ...
  28. // create the instance of the Dragon prefab class
  29. const dragon = new Dragon(this, 190, 120);
  30. // add the instance to the display list
  31. this.add.existing(dragon);
  32. // modify the 'angle' property of the instance
  33. dragon.angle = -30;
  34. ...
  35. }
  36. }
  37. 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.