document.body.style = 'margin:0;';
var config = {
type: Phaser.AUTO,
width: 22 * 16,
height: 11 * 16,
scene: { preload, create },
banner: false
};
function preload () {
this.load.image('mario-tiles', 'https://labs.phaser.io/assets/tilemaps/tiles/super-mario.png');
}
function create () {
this.add.text(10, 10, 'Click to remove Tile\n( Use shift to replace Tile)')
.setScale(1.25)
.setColor('black')
.setOrigin(0)
.setStyle({fontStyle: 'bold', fontFamily: 'Arial'})
.setDepth(100);
// Load a map from a 2D array of tile indices
var level = [
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], [ 0, 1, 2, 3, 0, 0, 0, 1, 2, 3, 0, 0, 1, 2, 3, 0, 0, 0, 1, 2, 3, 0, ], [ 0, 5, 6, 7, 0, 0, 0, 5, 6, 7, 0, 0, 5, 6, 7, 0, 0, 0, 5, 6, 7, 0, ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], [ 0, 0, 0, 14, 13, 14, 0, 0, 0, 0, 0, 0, 0, 0, 14, 13, 14, 0, 0, 0, 0, 0, ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], [ 0, 0, 14, 14, 14, 14, 14, 0, 0, 0, 15, 0, 0, 14, 14, 14, 14, 14, 0, 0, 0, 15, ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, ], [ 35, 36, 37, 0, 0, 0, 0, 0, 15, 15, 15, 35, 36, 37, 0, 0, 0, 0, 0, 15, 15, 15, ], [ 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, ] ]
// When loading from an array, make sure to specify the tileWidth and tileHeight
var map = this.make.tilemap({ data: level, tileWidth: 16, tileHeight: 16 });
var tiles = map.addTilesetImage('mario-tiles');
var layer = map.createLayer(0, tiles, 0, 0);
var shiftKey = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SHIFT);
// replace tile is blue tile
const NEW_TILE_INDEX_AFTER_REMOVE = 0
this.input.on('pointerdown', function({x,y}){
// replace Tile, when shift key is pressed
if(shiftKey && shiftKey.isDown){
let selectedTile = layer.getTileAtWorldXY(x,y);
// prevent error if tile doesn't exist
if(selectedTile){
layer.replaceByIndex(selectedTile.index, NEW_TILE_INDEX_AFTER_REMOVE, selectedTile.x, selectedTile.y, 1, 1);
}
} else {
// default action remove tile
layer.removeTileAtWorldXY(x,y);
}
});
}
new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/phaser@3.55.2/dist/phaser.js"></script>