I’m making a script that places objects in a random location with limits. I got the limits on where they can be placed working, but now I’m trying to make it so that parts don’t spawn inside other parts.
What is the issue?
I have absolutely no idea on how to do this.
3.*What solutions have you tried so far?
I tried making a “repeat” loop thingy and I tried to use functions, but I think I was using them the wrong way.
That’s pretty much it… I’m not very advanced in scripting, and I’d really appreciate help with this.
while wait(.25) do
local Part = Instance.new("Part")
Part.Parent = script.Parent
Part.Anchored = true
Part.Size = Vector3.new(1, 3, 1)
Part.BrickColor = BrickColor.Random()
local NewX = math.random(script.Parent.Attachment2.WorldPosition.X, script.Parent.Attachment1.WorldPosition.X)
local NewZ = math.random(script.Parent.Attachment1.WorldPosition.Z, script.Parent.Attachment2.WorldPosition.Z)
if script.Parent:FindFirstChild(NewX.. NewZ) == nil then
Part.Position = Vector3.new(NewX, script.Parent.Position.Y + 1, NewZ)
Part.Name = NewX..NewZ
print("Placed")
else
-- This is where I want the script to get a new position to put the part in.
Part:Destroy()
print("Destroyed")
end
--Part.Position = Vector3.new(NewX, script.Parent.Position.Y + 1, NewZ)
Part.Orientation = script.Parent.Orientation
end
local NewX = math.random(script.Parent.Attachment2.WorldPosition.X, script.Parent.Attachment1.WorldPosition.X)
local NewZ = math.random(script.Parent.Attachment1.WorldPosition.Z, script.Parent.Attachment2.WorldPosition.Z)
Have you made sure these attachment positions weren’t switched to where it might become math.random(max, min)?
Edit: this comment is deemed useless. read the one below
This should be your answer then:
Also, sorry for being late to reply.
if script.Parent:FindFirstChild(NewX.. NewZ) == nil then
Part.Position = Vector3.new(NewX, script.Parent.Position.Y + 1, NewZ)
Part.Name = NewX..NewZ
print("Placed")
else
-- This is where I want the script to get a new position to put the part in.
repeat
NewX = math.random(script.Parent.Attachment2.WorldPosition.X, script.Parent.Attachment1.WorldPosition.X)
NewZ = math.random(script.Parent.Attachment1.WorldPosition.Z, script.Parent.Attachment2.WorldPosition.Z)
wait()
until script.Parent:FindFirstChild(NewX..NewZ) == nil
Part.Position = Vector3.new(NewX, script.Parent.Position.Y + 1, NewZ)
Part.Name = NewX..NewZ
print("Replaced")
end
Make a raycast pointing to the randomly generated vector, from the same X and Z coordinates, and a high Y (usually your height limit), your item goes where the raycast hits, you may need to add an offset.