Skip to content

Instantly share code, notes, and snippets.

@bitbrain
Last active November 14, 2022 17:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bitbrain/0450452bd1aba6ac47bffa0c3c96a9bd to your computer and use it in GitHub Desktop.
Save bitbrain/0450452bd1aba6ac47bffa0c3c96a9bd to your computer and use it in GitHub Desktop.
Godot 4 Tilemap tricks
## Registers a tile with the tilemap that can then be placed
## via tile_map.set_cell(layer_index, map_coord, tile_id, Vector2i(0, 0))
func register_tile_and_get_id(tile_map:TileMap, texture:Texture2D, tile_size:int) -> int:
var tileset = tile_map.tile_set
var source = TileSetAtlasSource.new()
source.texture = texture
source.texture_region_size = Vector2i(tile_size, tile_size)
source.create_tile(Vector2i(0, 0))
return tileset.add_source(source)
## Places an autotile at position x,y (supports list of points)
func set_terrain(map_coords:Array[Vector2i]) -> void:
tile_map.set_cells_terrain_connect(0, map_coords, 0, 0, true)
## Noise texture that comes with its own noise editor in the properties section!
@export var noise:FastNoiseLite = FastNoiseLite.new()
## Given a terrain on a tileset, this code will generate a cave
## (noise may need to betweaked within the editor)
func generate_cave(tile_map:TileMap, map_w:int, map_h:int, seed:int, threshold:float) -> void:
noise.seed = seed
var air_positions:Array[Vector2i] = []
for x in range(-map_w / 2, map_w / 2):
for y in range(-map_h / 2, map_h / 2):
var tile_id = tile_map.get_cell_source_id(0, Vector2i(x, y), false)
# ensure we do not draw on already placed tiles
if tile_id != -1:
continue
var noise_value = noise.get_noise_2d(x, y)
elif threshold >= noise_value:
air_positions.append(Vector2i(x, y))
set_terrain(air_positions)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment