-- Sets the mass of the specified part by adjusting its density so that all
-- speeders will have the same mass (using static _DENSITY and _VOLUME)

local function SetMass(part)
	local volume = part.Size.X * part.Size.Y * part.Size.Z
	local newDensity = _DENSITY * _VOLUME / volume
	
	-- Defaults except newDensity (density, friction, elasticity)
	part.CustomPhysicalProperties = PhysicalProperties.new(newDensity, 0.3, 0.5)
end -- SetMass()


local function HandleCollision(collidedPart, part, self)
	local RaceTrack = workspace:FindFirstChild("Racetrack")
	local EnvironmentAssets = workspace:FindFirstChild("Environment Assets")
	local Plants = EnvironmentAssets:FindFirstChild("Plants")
	
	if not collidedPart:IsDescendantOf(self.speeder) and not collidedPart:IsDescendantOf(RaceTrack)
	 and not collidedPart:IsDescendantOf(Plants) and not (collidedPart == workspace.SpeederSpawnLocation) 
	 and not PhysicsService:CollisionGroupContainsPart(_SPEEDEROBJECTSCOLLISIONGROUP, collidedPart) then
		-- Create particle effect
		local particle = Explosion:Clone()
		particle.CFrame = part.CFrame
		particle.Parent = workspace


		character:Destroy()
		ExplosionSound:Play()
		
		local planeGui = PlayerGui:FindFirstChild("DesktopGui") or 
			PlayerGui:FindFirstChild("ConsoleGui") or
			PlayerGui:FindFirstChild("MobileGui")
		if planeGui then
			planeGui.Enabled = false
		end
	
		local emitterChildren = particle:GetChildren()
	
		for _, child in pairs(emitterChildren) do 
			-- If the child is a particle, then cause it to emit
			if child:IsA("ParticleEmitter") then
				child:Emit(10) 
			end
		end


		-- Destroy particle after PARTICLE_DURATION seconds
		spawn(function() 
			wait(PARTICLE_DURATION) 
			particle:Destroy() 
		end)
		-- Convert speeder to player
		spawn(function() 
			wait(2)
			PlayerConverter:SpeederToPlayer(false)
		end)	
	end
end -- handleCollisions()


local function SetupCollisionDetection(parent, self)
	for _,part in pairs(parent:GetChildren()) do
		if (part:IsA("BasePart") or part:IsA("MeshPart")) and part.Name ~= "Head" and 
			part.Name ~= "UpperTorso" and part.Name ~= "Arrow" then
			part.Touched:Connect(function(collidedPart) HandleCollision(collidedPart, part, self) end)
			SetupCollisionDetection(part, self)
		end
	end
end -- setupCollisionDetection()