So theres a problem in my car crashing system. Sometimes when it crashes or flips, it would break every weld constraint in the car.
Code: (client)
local model = script.Parent
model.Parent:WaitForChild(model.Name)
local Parts = model:WaitForChild("Parts")
local pushbackForce = 1
local function checkIfPartIsWelded(part)
if part then
local weldConstraint = part:FindFirstChildWhichIsA("WeldConstraint")
if weldConstraint then
return true
end
end
return false
end
local function onTouched(part, otherPart)
script.DestroyWeld:FireServer(part)
local positionDifference = (part.Position - otherPart.Position)
local distanceMoved = positionDifference.Magnitude
local pushBackFactor = (distanceMoved * pushbackForce)
local pushBackDirection = positionDifference.Unit
local surfaceNormal = otherPart.CFrame:VectorToObjectSpace(part.Position - otherPart.Position).Unit
pushBackDirection = (pushBackDirection + surfaceNormal).Unit
local pushBackDistance = -pushBackFactor
part:ApplyImpulse(pushBackDirection * pushBackDistance)
end
local function checkCanBreak(part, hit)
if hit:IsDescendantOf(model) then
local partWeld = part:FindFirstChildWhichIsA("WeldConstraint")
if partWeld and partWeld.Part1 == hit then
return false
elseif partWeld and partWeld.Part1 ~= hit then
return true
end
else
return true
end
return false
end
----------------------------------------------------------------------------------------------------------------------------------
local breakSpeed = 20
for i,v in ipairs(Parts:GetDescendants()) do
if v:IsA("BasePart") then
v.Touched:Connect(function(hit)
local speed = (v.AssemblyLinearVelocity - hit.AssemblyLinearVelocity).Magnitude
local Power = v:GetAttribute("Power")
local canBreak = checkCanBreak(v, hit)
if canBreak then
local isWelded = checkIfPartIsWelded(v)
if isWelded then
if Power and speed >= Power then
onTouched(v, hit)
elseif not Power and speed >= breakSpeed then
onTouched(v, hit)
end
end
end
end)
end
end
Game link: