Get a random tile's coordinates from an isometric tilemap

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

Hello Godot Experts,

I am trying to find and return a random tile’s vector2 coordinates from a 15x15 tilemap.

Image Reference

I would like for the sprites to individually choose a tile within a radius and then move to that tile as long as that tile isn’t already occupied by an object or another sprite.

I have the movement working but I’m struggling with the finding of the target position of the tile. Any idea on how to approach this?

Thank you for reading, if any more information is required, please ask. :slight_smile:

:bust_in_silhouette: Reply From: timothybrentwood
var top_left = Vector2(1,1) # your co-ords here
var bot_right = Vector2(16,16) # your co-ords here
randomize()
var random_vector = Vector2(randi() % int(bot_right.x - top_left.x) + top_left.x,
randi() % int(bot_right.y - top_left.y) + top_left.y)

randi() % R gives you a random number N that is 0 <= N < R

I would like for the sprites to individually choose a tile within a radius and then move to that tile as long as that tile isn’t already occupied by an object or another sprite.

You could use a RayCast2D and cast_to() the next tile you want to move to, if it collides just stop moving. However this won’t handle the case when two entities are trying to move to the same tile at the same time and you still need to find the path from your original position to your destination position.

To find the path I recommend using a AStar2D node. These will allow you to disable tiles with static bodies in them like your trees, when selecting a random position to move to you can check to see that the random position is enabled before choosing that position. A video demonstrating how to set one up: https://www.youtube.com/watch?v=Ad6Us73smNs

As far as handling the case where two entities are trying to move to the same tile at the same time… There are a couple methods, use the move_and_collide() function while moving and it you collide with something set your position to the last tile you were at. Some other people suggested that you ‘occupy’ the tile you’re moving to before you get there by putting a collision box into it that way whoever occupies it first gets to move to it. I personally created my own custom TileMap-like object that manages my own custom Tile objects. In my entity’s movement code I make them request a lock on the Tile object then only allow the entity to move to it if the tile is locked for that entity. You can read the details of that implementation here: https://forum.godotengine.org/102301/two-kinematic-bodies-occupying-same-discrete-square-area2d