How to use random position on models?

Hello!

I want to know how you can make models spawn in random positions!
Here is a line of code i am using:

	wall.Position = Vector3.new(math.random(-114, 12),15.1,math.random(-124, 33))

I want to know how you can make a model spawn in a random position.

Cheers! :wink:

2 Likes

Sure can:

local model = game.ReplicatedStorage:FindFirstChild("ModelToSpawn"):CLone()

model:SetPrimaryPartCFrame(
math.random(range),
groundlevel,
math.random(range)
)

Just be sure to set a primary part!

1 Like

Also, check out PivotTo(), “…the primary function that should be used to move Models via scripting.” (SetPrimaryPartCFrame has been superseded by PivotTo)

Like SetPrimaryPartCFrame, the PivotTo uses CFrame rather than a Position value (vect3).

-- CFrame is straightforward to use if you only care about the position.
local position = Vector3.new(math.random(-114, 12),15.1,math.random(-124, 33))
local cf = CFrame.new(position)
-- then
model:SetPrimaryPartCFrame(cf)
-- or
model:PivotTo(cf)

-- If you need rotation, then an angles CFrame needs to be combined with 
-- your position CFrame like so:
local cf = CFrame.new(position) * CFrame.Angles(math.rad(45), 0, 0)
5 Likes
local model = --[[path to model]]:Clone()
model:MoveTo(Vector3.new(math.random(range),15.1,math.random(range)))

It’s better to use PivotTo, since you don’t need a primaryPart for the model.