How do I place random objects above an uneven surface

I want to place coins, health pickups, or some other form of token, on uneven, randomly generated surface terrain. I don’t have any trouble generating random coordinates on the X and Z axis, but the Y eludes me and I wind up with tokens in really weird places. For example, in the code below, I might have a health token for which I’ve got an empty “HealthTokens” folder in the workspace. The token I intend to clone at random positions is in ServerStorage.

   local hToken = game:GetService("ServerStorage")["healthToken"]
   local xRnd = math.random(-512, 512)
   local zRnd = math.random(-512, 512)
   local pos =, 4, zRnd)
   local token = hToken:Clone()
   token.Parent = workspace.HealthTokens
   token.Position = pos

Now, if my surface was flat, the health tokens would float nicely at 4 studs above the surface, but with hills, lakes, valleys, etc, They could be inside a mountain or floating 30 feet in the air. How do I determine the actual position above ground when the ground isn’t flat?

Thanks for any enlightenment you can offer.

Maybe take random points of X and Z on the map, and then raycast down from the sky?

1 Like

I’d look into Raycasting and Raycast down from the Part enough to give the 4 studs height.

1 Like

First, my thanks to the people who suggesting raycasting might be the answer I was looking for. In the end, that most definitely did the trick. However, it took me some doing, experimenting, reading, and more experimenting to eventually figure out how to do this crazy thing. Once I had it figured out, I decided to make a video in case others want to see the result and how it was done.

Here’s the link to that video now.