I wanna make a script in order to spawn some parts in a specific area but it don’t work robloxapp-20220102-1836085.wmv (333.5 KB)
The part should stay in the black part but it don’t.

Here is my script :

function GenerateSpawnPosition(ZonePosition: Vector3, ZoneSize: Vector3, Part: Part): Vector3
local PositionX = math.random(-ZoneSize.X,ZoneSize.X)
local PositionZ = Part.Position.Z
local PositionY = math.random(-ZoneSize.Y,ZoneSize.Y)
return CFrame.new(PositionX, PositionY, PositionZ)
end
while wait(1) do
local test = GenerateSpawnPosition(game.Workspace.Zones.Zone1.Position, game.Workspace.Zones.Zone1.Size, game.Workspace.Part)
game.Workspace.Part.CFrame = test
end

You have a ZonePosition parameter but it never gets used the the function. That’s one hint that something is wrong. You also need to get a number between -HALF the size and +HALF the size on each axis. Here’s a version that should work:

function GenerateSpawnPosition(ZonePosition: Vector3, ZoneSize: Vector3, Part: Part): Vector3
local offsetX = math.random(-ZoneSize.X/2, ZoneSize.X/2)
local offsetY = Part.Position.Z/2 --Or leave it as it is if you want the top face of the zone.
local offsetZ = math.random(-ZoneSize.Y/2,ZoneSize.Y/2)
return CFrame.new(offsetX, offsetY, offsetZ) + ZonePosition
end

This version also only works if the part has a specific rotation, i.e. the Part’s X axis is same as the world X axis, and its Y axis is on the Z axis.

I don’t really understand why I have to use the half size on each axis, maybe you could send me some documentations or explain me why? I don’t really understand what is the relation between size, CFrame and position.

Nevertheless, the part seems to stay in the same Z axis so I fixed the script if someone would like to take it :

function GenerateSpawnPosition(ZonePosition: Vector3, ZoneSize: Vector3, Part: Part): Vector3
local offsetX = math.random(-ZoneSize.X/2, ZoneSize.X/2)
local offsetY = Part.Position.Y/2
local offsetZ = math.random(-ZoneSize.Z/2,ZoneSize.Z/2)
return CFrame.new(offsetX, offsetY, offsetZ) + ZonePosition
end

Positions of parts refers to their midpoints, which are in the middle, or halfway between the corners. To get to the lower left front corner, you must therefore subtract half the size, not the whole size. The other half of the size “goes to” getting the top right back corner, for which you must add half the size.