javascripttypescriptphaser-frameworktiledtmxtiledmap

Phaser3 Tiled Map Editor İmage Layer(can't use image layer for background)


I create an image layer in the tiled map editor, I place it on the map (I will use it as background) I get exported as json, I cannot use it in phaser3, but how to use it. I can use other layers, I can see them, but I can't see the image layer and technically it shouldn't be where I placed it in tiled, there is no problem in preload.

Edit ;

enter image description here


Solution

  • You should be able to get the images names from the image layers with the function getImageLayerNames link to the documentation, but I'm not 100% sure how it works since I never tried it.

    Update: I tried it now you would only need to get the image name from the property images from the map object.

    Mini Code:

    let map = this.add.tilemap('map');
    // if you know the imagelayer name, if not use the "getImageLayerNames" function to find the naes
    let bgName = 'BG';
    
    let imageOfImageLayer = map.images.find(layer => layer.name == bgName );
    // maybe check if it was found or not
    

    You would need to preload the first (or load it later in a more complicated way). if you use the filename as key it makes it easy.

    for example:

    preload(){
        this.load.image('bg.png', 'bg.png')
        // ...
    }
    

    And in the create function set them as any other image, with this.add.image(...), and the values from the layer.

    Update 2 / Solution:

    You would have to add the image, best in the create function. something like this:

    const BG_KEY = "background";
    
    class MyScene extends Phaser.Scene {
        ...
        preload(){
            this.load.image(BG_KEY , 'bg.png')
            // ...
        }
    
        create(){
            this.map = this.add.tilemap('map');
            // ...
            let imageOfImageLayer = this.map.images.find(
                (layer) => layer.name == BG_KEY 
            );
    
            this.add.image(imageOfImageLayer.x, imageOfImageLayer.y, imageOfImageLayer.name)
                // like this you can set the origin of the coordinates, by default it is in the middle
                .setOrigin(0,0);
            // ...
        }
    

    btw.: If you want to load images manually without using the preload function (because you want to use the filename provided in the tiled file), you can checkout this official phaser example, which shows how to manually load images, after preload.
    It's alot more work so I would not recomend it, if it is not 100% necessary.