-- Variables

local hasExploded = false

local function Explode()
	
	-- Don't allow this to execute multiple times
	if hasExploded then return end
	hasExploded = true
	
	wait(0.2)
	
	local Explosion = Instance.new("Explosion")
	Explosion.BlastRadius = 14
	Explosion.BlastPressure = 2000
	Explosion.DestroyJointRadiusPercent = 0

	Explosion.Position = RootModel:GetPrimaryPartCFrame().Position

	local parts = workspace:GetPartBoundsInRadius(Explosion.Position,Explosion.BlastRadius)

	-- So we don't rehit the same target multiple times
	local flaggedForHit = {}
	
	-- If the part is connected to a player character then apply damage
	for _, part in pairs(parts) do
		local character = PartUtility.GetCharacterFromInstance_R(part)
		if not character then continue end
		-- Don't rehit the same character multiple times
		if flaggedForHit[character] then continue end
		flaggedForHit[character] = true

		APICombat.ApplyDamageToCharacter(owningPlayer,character,WeaponDefinition)	
	end

	Explosion.Parent = workspace

	local effectPart = Instance.new("Part")
	effectPart.Position = Explosion.Position
	effectPart.Anchored = true
	effectPart.Transparency = 1
	effectPart.CanCollide = false
	effectPart.Parent = workspace

	-- Play sounds
	for _, effect in pairs(EffectsToPlay:GetChildren()) do
		effect.Parent = effectPart
		if effect:IsA("Sound") then
			effect:Play()
		end
	end

	DebrisService:AddItem(effectPart,4)

	RootModel:Destroy()
end

for _, part in pairs(RootModel:GetChildren()) do
	part.Touched:Connect(function(part)		
		local character = PartUtility.GetCharacterFromInstance_R(part)
		if owningPlayer.Character and owningPlayer.Character ~= character then
			Explode()
		end
	end)
end

