I am trying to convert some tiles into sprites so I can manipulate them. I have successfully done this but the sprite takes the whole of the tileset image (‘GS’):
let tiles = this.getVisibleTiles(scene);
let ids = tiles.map(a => a.index);
let s = scene.mapLayers['InteractionTiles'].createFromTiles(ids, null, { key: 'GS', frame: 17});
s.forEach(x => {
scene.add.existing(x);
//scene.physics.world.enable(x);
x.alpha = .5;
x.depth = 100;
});
tiles.forEach(t => {
scene.mapLayers['InteractionTiles'].removeTileAt(t.x, t.y)
});
let tilesAfter = this.getVisibleTiles(scene);
debugger;
Is there a way to get the image/frame from the tileset image or do I have to also create a sprite sheet from the same image?
Below are my attempts and what the result is:
let s = scene.mapLayers['InteractionTiles'].createFromTiles(ids, null, { key: 'ComponentSheet'});
This version selects the first frame:
let s = scene.mapLayers['InteractionTiles'].createFromTiles(ids);
this version cannot find the image:
I realise this is not a standard practice but I’ve solved it. createFromTiles
runs through and creates a sprite for ALL instances of that tile. I am kidnapping the tiles from the map, creating a container with them in as sprites instead (complicated physics is why).
Here is rough utility that does what I want which is convert the tiles in this area to a collection of sprites and add them to a container so they can be used as a group.
let container = new Phaser.GameObjects.Container(scene, this.body.x, this.body.y);
let s = Utils.TileAreaToSprites(tiles, { key: 'ComponentSheet' }, scene.mapLayers['InteractionTiles']);
s.forEach((x, i) => {
//adjust origin and position to macth use case
x.setOrigin(0);
x.x = 0;
x.y = i * 64;
});
container.depth = 100;
container.add(s);
scene.add.existing(container);
static TileAreaToSprites(tiles, spriteConfig, layer) {
if (spriteConfig === undefined) { spriteConfig = {}; }
let tilemapLayer = layer;//.tilemapLayer;
let scene = tilemapLayer.scene;
let camera = scene.cameras.main;
let sprites = [];
let i;
for (i = 0; i < tiles.length; i++) {
var tile = tiles[i];
if (tile.index !== -1) {
spriteConfig.x = tilemapLayer.tileToWorldX(tile.x, camera, layer);
spriteConfig.y = tilemapLayer.tileToWorldY(tile.y, camera, layer);
if (tile.index != -1)
spriteConfig.frame = tile.index -1;
else
delete spriteConfig.frame;
var sprite = scene.make.sprite(spriteConfig);
sprites.push(sprite);
}
}
return sprites;
};