How to instantiate a scene and make it be placed onto the ground which is an uneven mesh/collision?

Godot Version

4.4.1

Question

Hi,
I am trying to create a spawn area that will spawn lots of a scene onto the ground below it.

I have got a functioning area (collision shape) as the scene that randomly spawns multiples of another scene (collision and mesh).

I just cannot find a way to have the instantiated scene be placed on the ground below it. I was mostly trying to find a way to get a y position that is on the surface of the ground.

Here is what I have for the spawn area (from a tutorial on Youtube)

extends Area3D

var spawn_opject = preload("res://scenes/resourceAtomA.tscn")
var spawn_number = 10

var random = RandomNumberGenerator.new()

func _ready():
	spawn()

func getRandomPos(size) -> Vector3:
	random.randomize()
	var x = random.randf_range(-abs(size/2),abs(size/2))
	var z = random.randf_range(-abs(size/2),abs(size/2))

	var y = 1 ##### I need this to equal the surface of the mesh below #####
	
        # $MeshInstance3D/StaticBody3D/terrainCollision3D
	return Vector3(x,y,z)

func spawn():
	for i in spawn_number:	
		var obj = spawn_opject.instantiate()
		obj.position = getRandomPos(50)
		add_child(obj)

Would using raycast work? If so how would I do that?

I think raycasts would actually be the easiest way to do it.

  1. Find some y-position that the terrain will always be under, and one that the terrain will always be over. There might already be a maximum/minimum height you have set, you could decide on one now, or you could get the highest/lowest point in the mesh at runtime.
  2. In getRandomPos, use a raycast (ideally a low-level one, as described here) - with its origin at (x, “max_height”, z) and its target at (x, “min_height”, z) - to find the highest point of the terrain at that x/z position (The highest point is just the collision point because the raycast is shot from above). The y-component of this point will be y.