How would I generate a potato in a random area of a garden?

So take the garden bed’s X/Z dimensions(If the garden size is 5, 2, 8, the XZ dimensions are 5 and 8) by doing

local maxX, maxZ = gardenBed.Size.X, gardenBed.Size.Z

You then want to generate a random position in this, using math.random(). So do the following:

local randX = math.random(0, maxX)
local randZ = math.random(0, maxZ)

This will return a random whole number between 0 and MaxRange.

For the final positioning, you will want to set the potato’s position to the X and Z, but relative to the garden bed. So do this:

local potato = potatoReferenceToPart/ModelHere
-- The line below will get the gardenBed's CFrame in the 0, Y, 0 corner, so then you can add the x and z to it. Y is half the size of the gardenBed, so in the middle of the garden bed.
local gardenBedOffsetCF = CFrame.new(Vector3.new(gardenBed.CFrame.X - maxX, gardenBed.CFrame.Y, gardenBed.CFrame.Z - maxZ)

-- We now want to make the potato go to the X/Z relative to the gardenBed's offset CFrame
local relativePos = gardenBedOffsetCF:ToObjectSpace(CFrame.new(0,0,0))
-- Now we have a relative position to the corner of the garden bed.

-- We can now add our coordinates
local potatoPos = Vector3.new(relativePos + CFrame.new(randX, anyYValueThatMakesThePotatoTheRightHeightOutOfTheGround, randZ))

You can now set the potato’s position to the potatoPos, and it will be relative to the garden. If you want to convert it back to world space, you should use :ToWorldSpace(), linked from the API reference here

Of course, you will have to modify it a little bit to fit your needs, but the overall math should stay the same. I hope this helps, please mark as a solution so people can find this in google a few years from now!

1 Like