Let's say that I want to spawn a certain object randomly where a part takes up space, how would I make it so that I can make sure that it spawns an object in a location inside of the part's volume, assuming that the part is oriented in a non-90 degree increment rotation.
If you get a random number between negative half the size and positive half the size of the part on each axis, that will give you a random offset relative to its orientation. Since math.random
only works with integers, multiplying it by 100 before using math.random
will give a more accurate result (you then have to divide the result by 100 to get it back to its original state). Since we are getting only half of the size on each axis, instead of going Part.Size.X * 0.5 * 100
, you can simplify that to just Part.Size.X * 50
. After you have gotten the random offset for each axis, you can multiply these offsets from the original CFrame (multiplying the CFrame will offset it relative to its orientation), getting a final CFrame in a random position. To get the position from the CFrame, you can just use .p
.
local function GetRandomPosWithinPart(Part) local XOffset = math.random(-Part.Size.X*50,Part.Size.X*50)/100 local YOffset = math.random(-Part.Size.Y*50,Part.Size.Y*50)/100 local ZOffset = math.random(-Part.Size.Z*50,Part.Size.Z*50)/100 local CF = Part.CFrame * CFrame.new(XOffset,YOffset,ZOffset) return CF.p end
This is of course assuming the part is a normal cube/rectangular prism.