# How can I get a random position located through the size of the part?

I’m trying to get a random position so it is in the area of the part, but I have no idea how. I’m guessing I need to use Region3, but I don’t know how to use it.

4 Likes

Region3 is used to find parts inside a region. I’ve supplied some code that’ll work. RanPosition will be a random position inside of the part (or right on the edge)

local RNG = Random.new()
local Part = workspace.Part
local Position = Part.Position
local Size = Part.Size

local MinX , MaxX= Position.X - Size.X/2, Position.X + Size.X/2
local MinY, MaxY = Position.Y - Size.Y/2, Position.Y + Size.Y/2
local MinZ, MaxZ = Position.Z - Size.Z/2, Position.Z + Size.Z/2
local X, Y, Z = RNG:NextNumber(MinX, MaxX), RNG:NextNumber(MinY, MaxY), RNG:NextNumber(MinZ, MaxZ)

local RanPosition = Vector3.new(X, Y, Z)
2 Likes

I tried a similar method like this before, but the same thing happens:

Basically I am trying to make the bananas spawn within the area of that selected part, but it has trouble with doing rotated parts

This is what I tried before:
Part.CFrame = Location.CFrame + Vector3.new(math.random(-Location.Size.X/2,Location.Size.X/2),3,math.random(-Location.Size.Z/2,Location.Size.Z/2))

1 Like

Basically there will be a very low chance that they are positioned in the right place

1 Like

You need to do it all with CFrame since Vector3 has no rotation

function getRandomInPart(part)
local random = Random.new()
local randomCFrame = part.CFrame * CFrame.new(random:NextNumber(-part.Size.X/2,part.Size.X/2), random:NextNumber(-part.Size.Y/2,part.Size.Y/2), random:NextNumber(-part.Size.Z/2,part.Size.Z/2))
return randomCFrame
end
19 Likes

It works!
Thank you for the help @RSAiste @Kymaraaa

Please mark whoever’s code you used as a solution instead of marking your own (as it’s considered Solution Farming / Hogging and very much frowned upon)

Changed it straight away, it was not intentional.