–1 vote

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: 
        instance_enemy(enemy_position)
    else: 
        find_valid_position()

func instance_enemy(enemy_position):
    var enemy = enemy_scene.instance()
    add_child(enemy)
    enemy.position = enemy_position
Godot version 3.4
in Engine by (145 points)

1 Answer

0 votes
Best answer

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 findvalidposition(), 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 enemyposition private for findvalid_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.

by (5,252 points)
selected by

Super helpful, thanks!

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.