maximinus Posted September 17, 2018 Share Posted September 17, 2018 I'm using Phaser 3 + ES6 I have a class defined in the normal way for a scene: class TerminalScene extends Phaser.Scene { ... }; Now I want to add a helper class of my own to manage some aspect. For instance, I have a class that handles some text displaying. But this class needs access to function this.add.text. For the moment I do this: class SomeExample { constructor(func_add_text) { this.add_text = func_add_text; } add(string) { func_add_text(......); } }; // to call the add function in SomeExample: var my_class_instance = new SomeExample(this.add.text.bind(this.add)); my_class_instance.add('Hello, World'); There must be a better way of doing this. In other libraries, I would have access to the function by importing. What am I missing? Link to comment Share on other sites More sharing options...
necKros Posted September 17, 2018 Share Posted September 17, 2018 Scene.add is already a helper plugin that adds common GameObjects to the scene it pertains to. Given the heavy focus Phaser 3 has on scenes, almost all your classes will need the scene as a parameter for the constructor. That way you can add objects with the add function: class MyObject { constructor(scene) { scene.add.image(0,0,'foo') } } Or add them with add.existing, which you will need if you are creating classes that extend any GameObject: class MyObject { constructor(scene) { let image = new Phaser.GameObjects.Image(scene, 0, 0, 'foo') scene.add.existing(image) } } class MyObject extends Phaser.GameObjects.Image { constructor(scene, x, y, key, frame) { super(scene, x, y, key, frame) scene.add.existing(this) } } Link to comment Share on other sites More sharing options...
iKest Posted September 17, 2018 Share Posted September 17, 2018 class SomeExample { constructor(func_add_text) { this.add_text = func_add_text; } add(string) { return this.add_text(......); } }; // to call the add function in SomeExample: var my_class_instance = new SomeExample(this.add.text); my_class_instance.add('Hello, World'); or class SomeExample { constructor(func_add_text, scope) { this.add_text = func_add_text; this.scope = scope } add(string) { this.add_text.call(this.scope, string) } }; // to call the add function in SomeExample: var my_class_instance = new SomeExample(add.text, this); my_class_instance.add('Hello, World'); Link to comment Share on other sites More sharing options...
maximinus Posted September 17, 2018 Author Share Posted September 17, 2018 Thanks all. Passing over the scene (i.e, "this" from the scene object) seems the best way, although I was trying to avoid having a reference to all of it. At least it's consistent and avoids all those .bind() calls. Link to comment Share on other sites More sharing options...
Recommended Posts