0 votes

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
Godot version 3.4
in Engine by (172 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 (7,925 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 Frequently asked questions and 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 [email protected] with your username.