Variable value randomly turning into gigantic negative number?

local sword = script.Parent
local mm = require(workspace.MainModule)
local hitbox = sword.Handle
local bossHealthType = "Humanoid"
local boss = workspace:WaitForChild("Boss")
local swingAnim = 1
local cd = 0
local char
task.spawn(function()
	repeat
		if cd > 0 then
			cd -= .1
		end
		task.wait(.1)
	until false
end)
sword.Equipped:Connect(function(mouse)
	char = sword.Parent
end)
sword.Activated:Connect(function()
	print(cd)
	if cd == 0 then
		cd = .3
		if swingAnim == 1 then
			swingAnim = 2
			mm.PlayAnim(char.Humanoid, 118629266337390, "SwordSwing1")
		else
			swingAnim = 1
			mm.PlayAnim(char.Humanoid, 94428166254459, "SwordSwing2")
		end
	end
end)

in the activated event i have a print function that prints the current cooldown of the swing. for the first print it prints 0, as expected. anytime i try it afterwards, however, it somehow becomes a gigantic negative number??
Screenshot 2024-12-23 185440

That’s not gigantic. It’s actually super duper small, -0.00000000000000002775575615628914 to be precise. This value is effectively 0, and is caused by floating point inprecision when carrying out the mathematical operations involving the decimal values.

The simplest workaround is just to replace

if cd == 0 then

with

if math.abs(cd) < 0.001 then

Since the context is cooldowns, do cd <= 0. That way if it is well past 0 it will still be true

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.