Randomizing A Parts Position Inside of Another Part

How would I make a script that randomizes a part’s position in another part?

(Part A = Part that B goes into, Part B = part i’m trying to randomizes position.)
just doing this so it is easier to read.

If I make B a child of A then make B’s position A, it always will spawn in the exact middle of A. How would I randomize the part’s position while spawning? I want the part to spawn inside of A and choosing a random spot inside of it. I am aware math. Random exists, but I’m not quite sure how to use it and cannot find an article. (if someone can link it that would help).

You would want to account for Part A’s Size minus Part B’s Size on different axes, getting the minimum and maximum position potential. You could then use math.random(MinimumCalculated, MaximumCalculated) on each axes to generate their positioning, and then set the position of Part B to that new Vector. It would look something like this;

-- Make it easier to refer to the Parts' positions and sizes.
local PartAPos = PartA.Position
local PartASize = PartA.Size
local PartBSize = PartB.Size

-- Factor in PartA's goal position, while getting all viable number options in between the maximum position, while making sure PartB's size is factored in so it stays completely inside of PartA.
local newX = math.random((PartAPos.X - PartASize.X / 2) + PartBSize.X, (PartAPos.X + PartASize.X / 2) - PartBSize.X)
local newY = math.random((PartAPos.Y - PartASize.Y / 2) + PartBSize.Y, (PartAPos.Y + PartASize.Y / 2) - PartBSize.Y)
local newZ = math.random((PartAPos.Z - PartASize.Z / 2) + PartBSize.Z, (PartAPos.Z + PartASize.Z / 2) - PartBSize.Z)

-- Generate PartB's new position with the random vectors factored in.
local PartBNewPos = Vector3.new(newX, newY, newZ)

I’m sure there is a cleaner way to do this, this is just the basic concept of what you’d need to factor in in order for this to work. I also wrote this from scratch, so there may be some minor errors when plugging it into the coding engine :grimacing: I can’t get into studio atm.

Hope this helped!

1 Like
-- Define references to the parts
local partA = workspace.partA
local partB = workspace.partB

-- Calculate a random position within partA
local randomPositionInsidePartA = partA.Position - partA.Size/2 + Vector3.new(math.random()*partA.Size.X, math.random()*partA.Size.Y, math.random()*partA.Size.Z)

-- Assign the random position to partB
partB.Position = randomPositionInsidePartA

We compute a random position within ‘partA’ by subtracting half of its size from its position and adding a vector representing a random point within its dimensions.


Thank you! I need to learn more about vector3 and this helps.


This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.