How would I spawn objects randomly but they keep their Y value when the position changes?

I am currently working on a project, I already know how to spawn in random things using math.random but I want to know how I could make them randomly spawn in different spots but they keep their Y value.

I am using a ProximityPrompt to do all this, here is an image:

Screenshot_6

I want to make the part spawn in random positions each time the Prompt is triggered and I also want to make the part keep its Y value to 10 instead of changing it. I would like to do this because I will later make Models or NPC’s spawn in when the Prompt Triggers, I am currently trying to figure out how this would work.

Here is the Script I am using in ServerScriptService:

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ServerStorage = game:GetService("ServerStorage")
local Button = game:GetService("Workspace"):WaitForChild("Button")
local Prompt = Button.Button.PromptAttachment:WaitForChild("ProximityPrompt")

local Sounds = Button:WaitForChild("Sounds")
local Events = ServerStorage:WaitForChild("Events"):GetChildren()

Prompt.Triggered:Connect(function()
	Sounds.Press1:Play()
	
	local ClonedEvent = Events[math.random(1, #Events)]:Clone()
	ClonedEvent.Parent = workspace.Spawned
	
	print("Spawned " .. ClonedEvent.Name)
	
end)

I couldn’t really find any posts related to my problem, but I thought about putting in Number Values in the parts or models, and then the script would find these values and use them, but I think it would be too complicated to script.

What do I do?

There are many ways to do this, you can use:

  • math.clamp
    Argument 1: Your Number
    Argument 2: Minimum: number
    Argument 3: Maximum: number
 Object.Position = Vector3.new(Pos.X, math.clamp(Pos.Y, 10, 10), Pos.Z)
  • simply change the Y Axis to 10

  • Detect Change with GetPropertyChangedSignal()

Object:GetPropertyChangedSignal("Position"):Connect(function()
    local Pos = Object.Position

    Object.Position = Vector3.new(Pos.X, 10, Pos.Z) -- maintains old while only modifying Y
end)

You cant Change something without Changing it, that’s kind of illogical.

To position a part randomly you can do

part.Position.X = math.random(1,100) -- change to ur range
part.Position.Y = 10
part.Position.Z = math.random(1,100)

This might not be the most efficient but it works

Edit: do what the guy below said :+1:

You are unable to change a Single Axis by Itself, Instead you have to do what I did:

local Pos = Object.Position
Object.Position = Vector3.new(Pos.X, 10, Pos.Z)

which in this case is:

Vector3.new(math.random(1,100), 10, math.random(1,100))

(IF this works, give that guy Solution, not me)

1 Like
part.CFrame = CFrame.New(Vector3.New(math.random(1, 1000), part.CFrame.Position.Y, Vector3.New(math.random(1, 1000)), part.CFrame.LookVector)