How to add Tiled objects in Phaser with custom class?

How can I add coins with position, image and collisions as defined in Tiled, but using my custom class Game.Unit.Coin?

I created a Tiled map with two layers:

  • “coins” objects
  • “walls” tiles

Tiled screenshot

I defined custom collisions on coins:

Tiled screenshot

I created a custom Coin class in Tiled:

Game.Unit.Coin = class extends Phaser.Physics.Matter.Sprite {
    constructor(scene, x, y, texture) {
        super(scene.matter.world, x, y, texture);
        scene.add.existing(this);
    }
}

Here is my Phaser code:

// Loading assets
this.load.image("walls", "assets/tilesets/walls.png");
this.load.image("coins", "assets/tilesets/coins.png");
this.load.tilemapTiledJSON("test", "assets/maps/test.json");

// Creating map
var map = this.make.tilemap({key: "test"});

// Creating walls
var wallsTileset = map.addTilesetImage("tileBlack_02", "walls");
var wallsLayer = map.createStaticLayer("walls", wallsTileset, 0, 0);
wallsLayer.setCollisionBetween(1, 11);
this.matter.world.convertTilemapLayer(wallsLayer);

// Creating coins
var coinsTileset = map.addTilesetImage("spritesheet_coins", "coins");
// ???

Version
Tiled 1.4.2
Phaser 3.24.1

Maybe have a look at this topic?
I don’t think it’s exactly what you’re looking for, but maybe it’ll give you some pointers.

Thank you for your reply, i will watch this.

It’s worth mentioning that Phaser 3.50 will make the createFromObjects method on tilemaps more powerful. One of the new features is the ability to instantiate a custom class. Currently, however, I think the only way to do this is to manually iterate the object layer.

2 Likes