Random Coins Generation

The Problem
Hi there! I’m trying to make a system that coins spawn randomly generated by a script through the map, I know how to do this, but I don’t know how to make it work that it doesn’t spawn into the map decoration. For example that the coins don’t spawn inside a wall or tree.

What have I tried?
Well, I thought about making multiple region3’s and spawning the coins in separate regions. So that you manually make regions that are not inside a decoration. Another thing I thought to do it is with patfindingservice.

So my question is, what’s the best way to do this?

Thanks for reading and I hope you can help me out :slightly_smiling_face:


Have you tried a simpler approach? Mark out areas with parts that coins can spawn in. When spawning a coin, choose a random area, (bigger areas should have a higher change of being chosen) then choose a random position inside that area and spawn a coin there.

1 Like

I would get random positions inside your map, somewhere in the sky, and then raycast downwards. If it hits the floor, the spawn a coin there. Else, if it hits a decoration, don’t spawn a coin there.


Yeah, that was kind of what I meant on my first suggestion what I should try.

Oh ok. What went wrong with it?

1 Like

You can spawn the coin with all its parts CanCollide on, then use :GetTouchingParts() to see which parts the coin is touching. If it’s a map decoration, you can delete the coin and spawn it again, then repeat until it spawned somewhere where it’s not touching a map decoration.

local PartsTouching = Coin:GetTouchingParts() -- this returns a table of the parts it's touching
for i,v in pairs(PartsTouching) do
   -- if statement to check if it's a map decoration. if so, delete it and respawn it randomly somewhere else

Nothing, but I was curious if there are other, better ways.

1 Like

I think this’ the best solution so far I’ll try it out!

Here’s an idea:

First you generate a grid. Each grid cell has a size and number of coins in it.
You then give the coins a random position inside there cell.
When you then want to generate the coins we only need to check for nearby coins in neighboring cells or coins inside the cell. This defeats the purpose of :GetTouchingParts(), and that's good :GetTouchingParts()` uses about of resources a lot more than finding the Magnitude.

1 Like