How To Manage Resource Spawns

I have some questions about how to best manage resources in games. For example, let’s say that I would like to spawn treasure chests in random locations that players can then find to earn rewards.

1. Spawning Resources On The Ground
For either smooth terrain or block maps, the ground has varying elevations. So how do I spawn the treasure chest so that it sits on the ground (instead of under or over the terrain)? The chest is anchored.

2. Not Spawning Resources In Restricted Areas
I don’t want the resources to spawn in trees or on top of houses, for example. So how would I exclude the spawning from such parts or areas?

3. Keeping Track Of Spawn Population
I don’t want to over populate an area with treasure chests, so how should I keep track of my resource population and density?

Thank you for any suggestions that you can share.

1 Like

Put it in a Folder and do

#Folder:GetChildren() – it will return a number

if #Folder:GetChildren() < 10 then
    SpawnMore()
end

You can set up parts to cover areas you want the Items to spawn in and then do Random math

You can use RayCast to determine where the ground is and check if there is any Items nearby as well

Here’s some Sample Code for the Random Math bit

local x = Part.Position.X + math.random(Part.Size.X) - (Part.Size.X * 0.5)
local y = Part.Position.Y
local z = Part.Position.Z + math.random(Part.Size.Z) - (Part.Size.Z * 0.5)


Another method is you can place them in and make them work like Health Kits in OverWatch, but it won’t be 100% random.

2 Likes
  1. You can ray cast down onto the terrain using Workspace:FindPartOnRay() (Don’t worry, it should work with terrain as well)
  2. You can choose to only spawn it on terrain if you are using it, or if using parts your going to have to designate good and bad parts to spawn on. Probably the best way to do so would be to mark all of the terrain parts using the CollectionService and just check if the part found on the ray has the terrain tag.
  3. If I understand the problem correctly, you don’t just want to have a global limit on how many chests can be in the world at once, but you don’t want specific areas becoming over/under populated with chests. You can keep track of how many chests are in each 100x100 stud area by dividing the x and z coordinates of a chests location by 100 and rounding down, then formatting it to a string like ‘12 20’ to use as an index in a sparse list of regions and add 1 to the number of chests in that region. When a chest is opened or every so often, go through this list of regions and make sure that each region has just the right amount.
2 Likes