Health decreases faster after spamming key

So first, here’s my script:

local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")

local Mouse = Player:GetMouse()
local Camera = workspace.CurrentCamera



Mouse.Move:Connect(function()
	local CameraPosition = Camera.CFrame.Position
	local Direction = CFrame.new(CameraPosition, Mouse.Hit.Position)
	local HitObject = workspace:Raycast(CameraPosition,Direction.LookVector*300)
	
	if HitObject then
		local Path = HitObject.Instance.Parent
		if not Path:FindFirstChildOfClass("Humanoid") then
			Path = Path.Parent
			if not Path:FindFirstChildOfClass("Humanoid") then
				Path = nil
			end
		end
		
		if Path then
			local Player2 = Players:GetPlayerFromCharacter(Path)
			if Player2 then
				UserInputService.InputBegan:Connect(function(input)
					while task.wait() do
						local Eheld = UserInputService:IsKeyDown(Enum.KeyCode.E)
						if Eheld then
							Player2.Character:WaitForChild("Humanoid").Health = Player2.Character:WaitForChild("Humanoid").Health - 0.01
						end
					end
				end)
			end
		end
	end
end)

I just combined random scripts that I found on the devforum for what I was looking for (because I’m too dumb to write it myself), and basically when I hold E while aiming at a player, they should take damage, which works. But when I spam E and then hold it, the health decreases faster than normally.
Here’s a video of it:

I hope this makes sense.

I think it’s because each time you are pressing the button it runs the while loop:

while task.wait() do
	local Eheld = UserInputService:IsKeyDown(Enum.KeyCode.E)
	if Eheld then
		Player2.Character:WaitForChild("Humanoid").Health = Player2.Character:WaitForChild("Humanoid").Health - 0.01
	end
end

Try writing it differently so there’s a main while loop, that checks if the player is holding the key + I believe that you don’t have to check if there’s any input.

3 Likes

Oh yeah, I didn’t even notice that I still left the InputBegan in the script. Thanks!

1 Like

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