I want to make candy spawn within a spawn area but randomly, the code that I have is below but the code is not spawning them in the correct area, please correct this to the correct variations or even just scrap it and help me figure out the correct way.
candy.Position = Vector3.new(math.random(candyspawn.Position.X, candyspawn.Position.Y), candyspawn.Position.Y, math.random(candyspawn.Position.X, candyspawn.Position.Y))
** NOTE: The candy is spawning its just not spawning in the correct places **
Your logic is not working because it doesn't take the size of the part into account. If you visualize your part on the x and z axes, it would look a little bit like this:
Your part on a 2D plane +-------------------------------------+-----> zPos + zSize/2 | | | | | | | | | +-----> zPos | | | | | | | | | | +------------------+------------------+-----> zPos - zSize/2 | | | | | | | | | v v v xPos - xSize/2 xPos xPos + xSize/2
This means that the position on the x axis of a candy would be math.random(xPos - xSize/2 , xPos + xSize/2)
and the z axis would be math.random(zPos - zSize/2 , zPos + zSize/2)
. Applying the same logic to all three axes you get:
local x = math.random(part.Position.X - part.Size.X/2 , part.Position.X + part.Size.X/2) local y = math.random(part.Position.Y - part.Size.Y/2 , part.Position.Y + part.Size.Y/2) local z = math.random(part.Position.Z - part.Size.Z/2 , part.Position.Z + part.Size.Z/2) local spawnPos = Vector3.new(x , y , z)
1 is the lowest value and 20 is the highest value. Y will be somewhere between 1 and 20 as will X and Z.
placeToSpawn = Vector3.new(math.random(1, 20), math.random(1, 20), math.random(1, 20)) candy.Position = placeToSpawn