phaserjs / phaser

Phaser is a fun, free and fast 2D game framework for making HTML5 games for desktop and mobile web browsers, supporting Canvas and WebGL rendering.
https://phaser.io
MIT License
37.15k stars 7.1k forks source link

Matter Object toJson() throws exception #4263

Closed svdragster closed 5 years ago

svdragster commented 5 years ago

So far no solution on my forum thread: https://phaser.discourse.group/t/matterjs-and-tojson/443

Calling toJson() on MatterJS Objects results in the 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 ()
photonstorm commented 5 years ago

This works fine for me in both 3.15 and master branch:

var block = this.matter.add.sprite(400, 300, 'block');

var data = block.toJSON();

console.log(data);
svdragster commented 5 years ago

It seems to happen when the Scene that the sprite is added in has been stopped. I'm saving all game objects in the scene when switching to the main menu. Calling toJSON() before stopping the current scene seems to work fine. Is that intended behaviour?

photonstorm commented 5 years ago

That's because the Sprite no longer has a physics body, as the Scene has been stopped and the world cleared, so it can't read the x/y position from the body. This is too far outside the bounds of acceptable use to warrant changing I'm afraid.