Wednesday, March 27, 2019

14. Tilemap

We use this tileset from the website OpenGameArt.



This is the png image where each tile is 16 by 16 with spacing of 1 between them.



We have a scene with Node and a Sprite child. Set the texture of Sprite with the above image. Make sure to load image with 2D pixel preset using the Import tab next to Scene. Then we attach a script to Node which will generate our tile resource (tres) file. We can think of this as the atlas of all tiles that Godot can understand.



extends Node

var tile_size = Vector2(16, 16)
onready var texture = $Sprite.texture

func _ready():
    var col = 7
    var row = 5
    var ts = TileSet.new()
    for i in range(col):
        for j in range(row):
            var region = Rect2(i * tile_size.x + i, j * tile_size.y + j,
                               tile_size.x, tile_size.y)
            var id = i + j * 7
            ts.create_tile(id)
            ts.tile_set_texture(id, texture)
            ts.tile_set_region(id, region)
        ResourceSaver.save("res://tiles.tres", ts)



Even though we get 35 tiles, 10 are empty. After creating the tiles.tres file by running this scene, we can now test it. In a new scene, will will have the node of TileMap.


Set the cell size to 16 by 16, and resource to the tiles.tres file. Then we can paint the tiles. It is best to have a grid of 16 by 16 with snapping.


No comments:

Post a Comment