Godot Version
godot-4
Question
Hi, i am trying to make enemies spawn randomly on ‘walk-able’ tiles in on a tilemap, but i’m not very experienced with godot and cant figure out how to do that. Any help or examples would be appreciated.
godot-4
Hi, i am trying to make enemies spawn randomly on ‘walk-able’ tiles in on a tilemap, but i’m not very experienced with godot and cant figure out how to do that. Any help or examples would be appreciated.
is the map randomly generated (set_tile from code) also or from editor drawn
the map is drawn in the editor
You can get an array of all the tiles placed in a TileMap with get_used_cells(), then you iterate on that and use get_cell_source_id() to get the ID of the tile. If it matches a tile you want to spawn on, you roll for a spawn on those coordinates.
Or you can use get_used_cells_by_id() if you want to check only one specific ID.
In either case you’ll get a Vector2 array with the coordinates of valid tiles.
(remember to multiply by the tile size to get pixel coordinates)
I have managed to figure out this, it feels like it should work but all the mobs spawn
at the top left cell and get stuck.
@onready var tilesmap = $TileMap
@onready var tiles = tilesmap.get_used_cells_by_id(0, -1 ,Vector2(1, 0))
@export var enemy_number = 5
func _ready():
while enemy_number >= 0:
var crab = spawn_crab.instantiate()
var spawner = tiles[ randi() % tiles.size() ]
add_child(crab)
crab.position = spawner
enemy_number -= 1
what is this script actualy doing?
You are setting the pixel position of crab to the tile coordinates of spawner. As I said, you want to multiply the vector returned by the tilemap function by the pixel size of your tiles.
So something like crab.position = spawner * tilesmap.tile_set.tile_size since you stored the TileMap instance in tilesmap.
cool, it works now
Thanks for explaining
This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.