Hello. I am working on a game that lets you create vehicles and spawn them. However, some players make very big or detailed builds that can lag the server a lot. One of the lag causes is this function being played over and over again at 10-25+ times a second. How can I optimize and simplify this so the server isn’t too stressed?
The game goes through every block on the players plot and checks what other blocks are touching that block. If they are touching, then it returns that touching block so the main code can make a weldconstraint between the two.
local function getAdjacentParts(part,customhitbox)
--local target = nil
local function createLargerHitbox(part,c)
-- hitbox increase in studs
-- coroutine.resume(coroutine.create(function()
local n = 0.04
local clone = part:Clone()
clone.Parent = part.Parent
clone:ClearAllChildren()
-- clone.Transparency = 0.8
-- clone.BrickColor = BrickColor.Red()
if customhitbox then
if customhitbox["Size"] then
clone.Size = customhitbox["Size"]
end
if customhitbox["Position"] then
clone.CFrame = CFrame.new(customhitbox["Position"])
end
else
clone.CFrame = part.CFrame
end
if (clone:IsA("WedgePart")) then
if c == 2 then
clone.Size = clone.Size + Vector3.new(n, n, -.5)
clone.CFrame = part.CFrame * CFrame.new(0, -n --[[/ 2]], 0)
--local taso = clone:Clone()
--taso.Parent = workspace
--taso.Anchored = true
--taso.Transparency = 0
--taso.Position += Vector3.new(0,15,0)
elseif c == 3 then
clone.Size = clone.Size + Vector3.new(n, -.5, n)
clone.CFrame = part.CFrame * CFrame.new(0, 0, n)
--local taso = clone:Clone()
--taso.Parent = workspace
--taso.Anchored = true
--taso.Transparency = 0
--taso.Position += Vector3.new(0,15,0)
end
elseif (clone:IsA("CornerWedgePart")) then
if c == 1 then
clone.Size = clone.Size + Vector3.new(n, -.5, -.5)
clone.CFrame = part.CFrame * CFrame.new(-n / 2, 0, 0)
elseif c == 2 then
clone.Size = clone.Size + Vector3.new(-.5, n, -.5)
clone.CFrame = part.CFrame * CFrame.new(0, n / 2, 0)
elseif c == 3 then
clone.Size = clone.Size + Vector3.new(-.5, -.5, n)
clone.CFrame = part.CFrame * CFrame.new(0, 0, n / 2)
end
else
if c == 1 then
clone.Size = clone.Size + Vector3.new(n, -.5, -.5)
elseif c == 2 then
clone.Size = clone.Size + Vector3.new(-.5, n, -.5)
elseif c == 3 then
clone.Size = clone.Size + Vector3.new(-.5, -.5, n)
else
clone.Size = clone.Size + Vector3.new(n, n, n)
end
end
clone.Name = "clone"
return clone
-- end))
--repeat wait(0) until target
--return target
end
local touchingparts = {}
if part.CanTouch == false then
return
end
for i = 1,3 do
local hitbox = createLargerHitbox(part,i)
local tp = hitbox:getTouchingParts()
for _, b in pairs(tp) do
touchingparts[#touchingparts+1] = b
end
hitbox:Destroy()
end
return touchingparts
end