I have a texture tileset, then I want to create a new object where the reference is from the tiles that are already in the tilesets.
how should i start ?
for now I use the renderTexture function to draw the required tiles from the tilesets, then take a snapshot so that I can retrieve them as new, drawable textures.
// mapping tiles
const tiles = [ [0, 1], [2, 3] ]
// my funct to get tiles from tilesets, and draw to render texture (crop, dll)
const toRenderTx = getRenderTexture(tiles)
// draw
const sprite = this.scene.physics.add.image(0, 0, toRenderTx)
// fc
getRenderTexture(tiles: number[][], key = 'default') {
const tileset = 'my-tileset'
const sourceTexture = this.scene.mapManager.tileMap?.getTileset(
tileset
) as Phaser.Tilemaps.Tileset
const { tileWidth, tileHeight } = sourceTexture
const tileIds = tiles
const rt = this.scene.make.renderTexture(
{
width: tileIds[0].length * tileWidth,
height: tileIds.length * tileHeight,
x: 0,
y: 0,
},
false
)
for (let y = 0; y < tileIds.length; y++) {
// loop X
for (let x = 0; x < tileIds[y].length; x++) {
const tileId = tileIds[y][x]
const coordinate = (sourceTexture.getTileTextureCoordinates(tileId) || {
x: 0,
y: 0,
}) as { x: number; y: number }
const ft = sourceTexture.image.get().clone()
const newRT = this.scene.make.renderTexture(
{
width: ft.width,
height: ft.height,
},
false
)
newRT.draw(ft)
newRT.setCrop(coordinate.x, coordinate.y, tileWidth, tileHeight)
rt.draw(
newRT,
-coordinate.x + x * tileWidth,
-coordinate.y + y * tileHeight
)
}
}
return rt.texture
}
but it turns out that this method causes a very large and uncontrolled memory.
with 6 object like code above, use 3.8gb of ram.
then, in the case of the code below why doesn’t it seem to work? only renders the first index.
for (let y = 0; y < tileIds.length; y++) {
for (let x = 0; x < tileIds[y].length; x++) {
const tileId = tileIds[y][x]
rt.drawFrame(tileset, tileId, x * tileWidth, y * tileHeight)
}
}
but when i try to change it to like this it seems to work.
for (let y = 0; y < tileIds.length; y++) {
for (let x = 0; x < tileIds[y].length; x++) {
const tileId = tileIds[y][x]
const newRT = scene.make.renderTexture(
{
width: tileWidth,
height: tileHeight,
},
false
)
newRT.drawFrame(tileset, tileId, 0, 0)
rt.draw(newRT, x * tileWidth, y * tileHeight)
}
}
I don’t know why, but when I tried it again it suddenly worked.
thanks for your help once again.
I want to ask a final question, is this a safe way to create objects?
I’m planning on creating a lot of objects this way actually, because instead of reloading the sprites, using the layout of the existing tileset for the tilemap I think makes sense.