Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do I get parts to spawn randomly inside the bounderies of a part?

Asked by
uhTeddy 101
5 years ago
Edited 5 years ago

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 **

2 answers

Log in to vote
2
Answered by
RayCurse 1518 Moderation Voter
5 years ago
Edited 5 years ago

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)
0
Thanks! uhTeddy 101 — 5y
0
No problem! RayCurse 1518 — 5y
Ad
Log in to vote
-2
Answered by 5 years ago
Edited 5 years ago

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
0
This isn't what Im looking for uhTeddy 101 — 5y

Answer this question