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:
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):
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.
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.
I share your opinion for the large part, I believe that
some points are worth having a more detailed appearance to comprehend what’s happening.
Each of us has a suitable understanding of the advice given to the public, so I truly liked the
article and expected you to provide us with more things like this one.