Search code examples
godotgdscriptgodot4

How to find or refer to instantinated 3Dobject by coordinates?


I have a procedural generated map like this (All rooms and tunnels made from planes 2x2m with instantinate()): enter image description here I want to fill all empty space by cubes. I have a coordinates of all rooms and tunnels, but I think that's too difficult and long way. I want to get a code like this:

var coord = Vector3i(0,0,0)
var new_cube
var cube = preload("res://assets/cube.tscn")

for x in range(32):
   coord.x += 2
   for y in range(32):
      if y == 0: crood.z = 0
      coord.z -= 2
      if is_something_on_coordinates(coord): continue
      new_fld=cube.instantiate()
      add_child(new_cube)
      new_cube.global_translate(coord)

I tried to find a way to find an object on the coordinates, but all that I found is for 2d canvas or for manually created objects.


Solution

  • You say each one of your rooms have a position and a size.

    The idea is as follows: Each room has a range for each of its coordinates, which goes from its position to its position plus size.

    Let us say, for example, that we are only looking at the x coordinate. Then each room has a range that goes from position.x to position.x + size.x.

    I'll also assume there are no negative sizes, so position.x + size.x is greater than position.x for any particular room.

    Now we can take our current position in x and see if it is in the range of any room:

    var found_room := false
    for room in rooms:
        if x > room.position.x and x < room.position.x + room.size.x:
            found_room = true
            break
    

    Of course, that only ensures that we are in the x range of the room. We might still be outside of the room in the other coordinate. But if your position is in range for all coordinates, it means it is inside the rectangle. Thus: repeat the same check for the other coordinate.

    There are other possible optimizations, but you probably don't need then for your map size. However a common idea is this: building - while generating the rooms - some structures in memory that makes easy finding a room given a position (the simplest of these would be arrays sorted by coordinates, and the more complex involve some kind of space partitioning).