--Make sure this script is inside a body of a car that you want to be destructible.
--Also this is mostly meant for cars which are made out of parts.

local Body = script.Parent
local BreakSpeed = 30

for _,Part in ipairs(Body:GetDescendants()) do
	if Part:IsA("BasePart") then
		Part.Touched:Connect(function(hit)
			local velocity = Part.Velocity.Magnitude -- Get the speed of the car
			local collisionforce = GetImpactVelocity(Part,hit)
			local h = hit.Parent:findFirstChild("Humanoid") or hit.Parent.Parent:findFirstChild("Humanoid")
			if collisionforce > BreakSpeed and h == nil then
				Part:BreakJoints()
				Part.Massless = true
				Part.CanTouch = false
				-- you can make so that a sound plays, or an effect appears etc...
				game:GetService("Debris"):AddItem(Part,10)
			end
		end)
	end
end

function GetImpactVelocity(part, Other)
	--dont touch this
	local pVelocity = part.Velocity
	local oVelocity = Other.Velocity

	local pRoundedVelocity = Vector3.new(math.floor(pVelocity.X), math.floor(pVelocity.Y), math.floor(pVelocity.Z))
	local oRoundedVelocity = Vector3.new(math.floor(oVelocity.X), math.floor(oVelocity.Y), math.floor(oVelocity.Z))

	local impactForce = Vector3.new(pRoundedVelocity.X - oRoundedVelocity.X, pRoundedVelocity.Y - oRoundedVelocity.Y, pRoundedVelocity.Z - oRoundedVelocity.Z)
	impactForce = Vector3.new(math.abs(impactForce.X), math.abs(impactForce.Y), math.abs(impactForce.Z))

	local speed = math.max(impactForce.X, impactForce.Y, impactForce.Z)

	return speed
end
