Spawning enemies only on a specific TileMap?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By samjmiller

I’m making a 2D action RPG and created a spawner for randomly placing enemies; works great EXCEPT I would love to only spawn enemies on the tilemap I created for the road.

When the timer times out, it calls a function to find a valid position, which randomly generates locations and then (in theory) checks them against the tilemap - if it’s a match, it calls the instance_enemy() function, if not, it loops back to generate and test another position, etc.

But, nah, enemies spawning all over the map.

Has anybody done something like this, and can share how it was done? The code for my “instance_enemy” and “find valid position” functions are, below but I may be going at this all wrong - feel free to send me back to the drawing board altogether!

Appreciate the help friends.

func find_valid_position(): 
	enemy_position.x = rng.randi_range(-500, 500)
	enemy_position.y = rng.randi_range(-500, 500)
	var cell_coord = tilemap.world_to_map(enemy_position)
	var cell_type_id = tilemap.get_cellv(cell_coord)
	if cell_type_id == -1: 

func instance_enemy(enemy_position):
	var enemy = enemy_scene.instance()
	enemy.position = enemy_position
:bust_in_silhouette: Reply From: Inces

Function seems valid. But I can see You using high scope ( introduced at the beginning of script ) variable enemy position. I guess, that whatever function is externally calling find_valid_position(), it is calling it simultanously for all enemies, so high scope variable is changed many times in single frame, determining random location without regards to the rest of the code in function. Try to make variable enemy_position private for find_valid_position() ( introduce it inside function ).

By the way, tile of index -1 can’t possibly be your road tile, -1 indicates that there is no tile.

Super helpful, thanks!

samjmiller | 2022-01-19 20:08