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

Returning random vector3 values that are inside a volume of a part?

Asked by 5 years ago

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.

0
You would need to calculate the 6 corners (assuming your working with regular brick parts here) and find the max and min x,y,z values out of them. LateralLace 297 — 5y
0
From there you'd subtract the max from the min values to get the area, which you could test to see if it fit within the bounds of the part's volume. LateralLace 297 — 5y

1 answer

Log in to vote
0
Answered by
mattscy 3725 Moderation Voter Community Moderator
5 years ago
Edited 5 years ago

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.

Ad

Answer this question