I am trying to make a brick that will give you money when you touch it, but I want it to spawn on random location so that it's not so easy to find. So my question is: How do I make a brick with a script in it that spawns on a random location (not in the air)?
You can use math.random()
to get around this. Basically you can generate a random x and z coordinate and keep a static y coordinate. If you do not want a part to be spawned 2 times in the same place you could use a table to store the previous vectors and check if the same vectors has been indexed or not. And alternatively if you do not want your part to collide with in-game models such as trees you could check if the place where you'd put your part is occupied by other objects. You could do this with region3. Here is a simple code I wrote which generates random parts:
local cache = {} while wait(0.1) do local randomVector = Vector3.new(math.random(-255, 255), 0.5, math.random(-255, 255)) if cache[randomVector] then repeat randomVector = Vector3.new(math.random(-255, 255), 0.5, math.random(-255, 255)) until not cache[randomVector] local part = Instance.new("Part") part.Parent = workspace part.Position = randomVector else local part = Instance.new("Part") part.Parent = workspace part.Position = randomVector end end
It is not really good you can improve yours by adding different functionalities as I said above. You could convert your parts to a region3 and then use workspace:FindPartsInRegion3(region) to check if the place where you'd put your part would be occupied by other objects. You could use this function to make the job easier for you:
local function partToRegion(Part) return Region3.new( Part.Position - ( Part.Size / 2), Part.Position + ( Part.Size / 2) ); end