-- Anytime a weapon is eqipped the weapons spread is displayed

local function DisplaySpreadForWeapon(tool)
	
	if steppedHandle then
		steppedHandle:Disconnect()
	end
	
	-- Get the weapons definition by the tool
	local weaponDefinition = APIEquipment.GetWeaponDefinitionFromTool(tool)
	
	-- Get the runtime of the weapon by the definition
	local weaponRuntime = APIEquipment.WaitForLocalCurrentWeaponRuntimeData(weaponDefinition)
	
	-- Get the spread simulator
	local spreadSimulator = weaponRuntime:GetSpreadSimulator()
	
	local characterState = APICharacterState.GetCharacterState()
	
	-- Interpolate crosshair based on spread
	steppedHandle = RunService.Stepped:Connect(function(currentTime,dt)
		
		-- Hide the crosshair when the player aims their weapon
		if characterState:GetAttribute("IsAiming") then
			Crosshair_Image.ImageTransparency = math.clamp(Crosshair_Image.ImageTransparency + dt * 10,0,1)
		else
			Crosshair_Image.ImageTransparency = math.clamp(Crosshair_Image.ImageTransparency - dt * 10,0,1)
		end
		
		-- Display the spread visuallly based on the weapons spread runtime data
		if spreadSimulator then
			local currentSpread = spreadSimulator:GetSpreadScreenMagnitude(workspace.CurrentCamera)
			Crosshair_Frame.Size = UDim2.new(0,currentSpread,0,currentSpread)
		else
			Crosshair_Frame.Size = UDim2.new(0,10,0,10)
		end
		
	end)
	
end

local character = Local_Player.Character

if character then
	character.ChildAdded:Connect(function(child)
		if not child:IsA("Tool") then return end
		DisplaySpreadForWeapon(child)
	end)
end

Local_Player.CharacterAdded:Connect(function(character)
	character.ChildAdded:Connect(function(child)
		if not child:IsA("Tool") then return end
		DisplaySpreadForWeapon(child)
	end)
end)

