I am currently developing my first tile based browser game and since I am rather a web developer with little knowledge about best practices in tile-based games, I was wondering how to move a tile around.
My first approach was to have a MoveTile object and with every move it would just do the normal update-call of:
this.x += new_x // Including direction, speed, dt etc
this.y += new_y // Same
I figured out pretty fast that moving the entire tile was not optimal and would lead to further problems with the collision detection and overall keeping track of where a tile is at the moment.
Luckily a friend of mine, who has more experiences in building games, had a good tip for me. Instead of giving a Tile-Object directly a texture/graphic, the Tile-Object has a child-element, which I called Sprite.
// Code excerpt / pseudo code
var MoveTile = function(options) {
this.row = options.row;
this.col = options.col;
// ...
this.sprite = new Sprite(sprite_options);
this.sprite_move_offset = 25;
}// And the Sprite object:
var Sprite = function(options) {
this.x = TILE_SIZE * options.row;
this.y = TILE_SIZE * options.col;
this.image = new Image();
this.image.src = options.image_path;
}
The important Tile property here is the MoveTile.sprite.move_offset. Lets consider our map consists of tiles with a size of 50x50. Instead of moving our MoveTile, we move the MoveTile.sprite object. If the Sprite-Object position relatively oversteps the sprite_move_offset (=25), then also move the MoveTile in the actual grid (means for going down: Tile.row + 1, Tile.col)
MoveTile.update = function(dt) {
this.y += this.speed * dt * this.vy; // vy is 0, 1 or -1
this.x += this.speed * dt * this.vx;
// Check the position of the Sprite and if it oversteps
// too much the MoveTile (this) object position, then change
// cell position
if (this.sprite.y > this.y + this.height - this.move_offset) {
this.row += 1;
} // Check for overstepping the upper part
if (this.sprite.y < this.y - this.move_offset) {
this.row -= 1;
} // Same for horizontal movement ...}
Now with this it is also pretty easy to check for collisions. If we know that the next Tile is for example a WallTile, then we just move the Sprite-Object until the border of the “parent” MoveTile.