Search code examples
jsonphaser-framework2d-games

PhaserJS collision tilemap not working


I have a tilemap that only 1 layer is correctly colliding with the player. Been through all the examples, but i can't seem to get it working on multiple layers.

I have 1 tilemap that contains all the json data for a total of 13 layers, but for the example i have only included 3.

I would like for the player to collide with different layers and have different callbacks, e.g. cannot walk through, pick up item if within range etc. but all using 1 spritemap/tilemap.

var game = new Phaser.Game(1200, 780, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render });

function preload() {
        this.load.tilemap('main_map', 'img here', null, Phaser.Tilemap.TILED_JSON);
        this.load.image('sprite_map', 'img here');
        this.load.image('player_image', 'img here');
}

var map;
var tileset;
var bLayer;
var wLayer;
var player;
var sLayer;
var cursors;

function create() {

    game.physics.startSystem(Phaser.Physics.ARCADE);

    // initiallize the tilemap
    map = game.add.tilemap('main_map');
    map.addTilesetImage('otherNew', 'sprite_map');

    //draw the layers 
    bLayer = map.createLayer(0);
    wLayer = map.createLayer(1);
    sLayer = map.createLayer(2);
    wLayer.resizeWorld();

    player = game.add.sprite(600, 600, 'player_image');
    game.physics.arcade.enable(player);
    player.body.collideWorldBounds = true;  // works

    //game camera and movment keys here 

}
function update() {
    game.physics.arcade.collide(player, wLayer); // DOES NOT WORK
    game.physics.arcade.collide(player, sLayer); // THIS WORKS
    map.setCollision(1, true, wLayer); // DOES NOT WORK
    map.setCollision(2, true, sLayer); // THIS WORKS 

   //movement here already works so didn't include

}

Solution

  • The answer is that each layer has its own set of tilemaps, and as i was using a spritesheet to generate each layer, those layers had some value that needed to be set. I didn't have the patience to check what actual collision layer I needed, but as I had split them all up into separate logical layers I just set between 0, 100 for each.

    // In the create section    
    map.setCollisionBetween(0, 100,true, wLayer,true);
    map.setCollisionBetween(0, 100,true, sLayer,true);