Tilemap

Using tilemaps is a great way to conserve memory usage. Instead of using large preset pictures as the background, object or platform entities in your game, you can use a picture of many different tiles and construct your game-world with those.

First, you add a new tile layer:

html5_tutorial_mightyeditor_tilemap

 

Then, adjust the TileLayer settings, most importantly the:

  • widthInTiles – tilemap grid width;
  • heightInTiles – tilemap grid height;
  • tileWidth & tileHeight – the dimensions of individual tilemap grid cells.

Then divide your spritesheet into frames (should be the same size as the dimensions of the tilemap grid cells):

html5_tutorial_mightyeditor_tilemap_2

And now, with the TileLayer object and tileset spritesheet asset selected, just select the specific frame that you want to place and click inside the TileLayer rectangle to place it on the map. You can hold the mouse button to cover larger areas without clicking. Hold CTRL to remove a tile.

html5_tutorial_mightyeditor_tilemap_3

Now we can add some collision to the tilemap. The best part is – we can do that to specific frames (frame count starts with 0):

"use strict";
window.Tilemap.state.menu = {
    create: function() {
        //create objects as usual
        this.tiles = mt.create("tiles");
        this.box = mt.create("box_simple");

        //play with different collision methods by uncommenting code:
        //uncomment to see collision borders
        //this.tiles.debug = true;

        //enables collision only with the 2nd frame of the spritesheet (brown blocks)
        this.tiles.map.setCollision(2);

        //enables collision with all frames in between the two values (here, the first four frames
        //this.tiles.map.setCollisionBetween(0,3);

        //enables collision with all frames EXCEPT those listed
        //this.tiles.map.setCollisionByExclusion([0,1,4,5,6,7,8,11]);


        this.cursors = this.game.input.keyboard.createCursorKeys();
    },


    update: function() {
        //check for collision between the character and tileLayer
        this.game.physics.arcade.collide(this.box, this.tiles);

        //character controls
        if (this.cursors.up.isDown)
            this.box.body.velocity.y = -200;
        else if (this.cursors.down.isDown)
            this.box.body.velocity.y = 200;
        else this.box.body.velocity.y = 0;

        if (this.cursors.right.isDown)
            this.box.body.velocity.x = 200;
        else if (this.cursors.left.isDown)
            this.box.body.velocity.x = -200;
        else this.box.body.velocity.x = 0;
    }
};

Full sample available here.

Leave a Reply

Your email address will not be published. Required fields are marked *