MatterJS and toJson()

Hello there, I’m creating matterjs objects like this (and storing them in an array afterwards):
this.matter.add.sprite(x, y, "platform")
Upon calling JSON.stringify() on my Array, I’m greeted with this exception:

Uncaught TypeError: Cannot read property ‘position’ of undefined
at MatterSprite.get [as x] (phaser.js:166821)
at Object.ToJSON (phaser.js:94119)
at MatterSprite.toJSON (phaser.js:11382)
at JSON.stringify ()

Is there a bug in Phaser or am I doing something wrong here?
Thanks in advance.

Hi, can you post the code where you create the array and the code where you add the objects to it.

Hi, thanks for your message.

class World {
  constructor() {
    this.name        = "This is my world",
    this.gameObjects = [];
    console.log(this);
  }

  store(gameObj) {
    this.gameObjects.push(gameObj);
    console.log(this.gameObjects);
    return gameObj;
  }

  toJson() {
    return JSON.stringify(this.gameObjects);
  }
}

I’m creating the sprite using the following code after creating an instance of World. Calling myWorld.toJson() results in the exception shown above. All of this is happening in the create function of my scene.

var sprite = this.matter.add.sprite(x, y, "platform")
console.log(sprite);
myWorld.store(sprite);
1 Like

The issue was that I stopped the current scene and then called myWorld.toJson(). I thought I was able to reproduce this even when calling myWorld.toJson() independent of that, I guess I messed that up.