Estoy tratando de crear un archivo js con funciones relevantes para mi juego, pero aparece un mensaje de error que dice
TypeError no capturado: no se pueden leer las propiedades de undefined (leyendo 'agregar')
cuando trato de usar funciones de phaser fuera del archivo principal.
Tengo 2 archivos, uno llamado game.js y otro llamado test.js También estoy usando el motor de física de la materia.
juego.js:
class bootScene extends Phaser.Scene { //Preloading assets for later use preload() { this.load.image('linus', 'assets/linus.png'); this.load.script('t','test.js') } create() { } update() { //launch game scene this.scene.launch('game').stop(); } } class playScene extends Phaser.Scene { constructor() { super('game'); } create() { test('test',1,1,'linus'); } update() { } } // set the configuration of the game let config = { type: Phaser.WEBGL, // Phaser will use WebGL if available, if not it will use Canvas width: 1280, height: 720, pixelArt: true, transparent: false, autoCenter: true, backgroundColor: '#000000', physics: { default: 'matter', matter: { restingThresh: 2, // debug: { // renderFill: false // }, gravity: { y: 0 } } }, scene: [bootScene, playScene] }; // create a new game, pass the configuration let game = new Phaser.Game(config);prueba.js:
function test(msg,x,y,texture){ console.log(msg) this.matter.add.image(x,y,texture) } Intenté poner t.test(etc.) y agregar el script de carga en precarga. Intenté buscar ejemplos, pero no pude encontrar ninguno.
Lo siento si esta es una solución realmente obvia o simplemente soy terrible
Solo necesita pasar la scene actual, como un parámetro, a la función de test , y podrá acceder al objeto de matter y otras propiedades / funciones, desde la scene .
function test(scene, msg, x, y, texture) { console.log(msg); scene.matter.add.image(x, y, texture); } Y habría que llamar a la test de función, con la "escena actual" en el caso de que sea this :
... create() { ... test(this, 'test', 1, 1, 'linus'); ... } Este ejemplo del sitio web oficial : Example Script Loading , ilustra este hecho indirectamente. En ese ejemplo, la scene no se pasa como parámetro, pero sí el canvas y el context .
Entonces, siguiendo este ejemplo, pasar la scene debería resolver su problema.
Nota al margen: en general, si no hay una razón específica, para cargar scripts desde el interior de una aplicación Phaser (como se muestra arriba) , cargaría los scripts dentro del archivo html o usaría un paquete web como webpack u otros. No solo por motivos de rendimiento/minificación.