So i'm trying to make it so when a player holds spacebar for 2 seconds player's character will receive a bodyvelocity but the player wont jump unless the spacebar is pressed/held for less than 2 seconds. The bodyvelocity will allow the player to fly but that's not the issue, the issue is the actual adding of bodyvelocity. My attempt ended up being quite a bit messy to the point where i can't even see my own mistake.
The attempt:
local uis = game:GetService("UserInputService")
local holding = false
local maxtime = 2
local debounce = true
local runservice = game:GetService("RunService")
uis.InputBegan:Connect(function(input, gameprocess)
if input.KeyCode == Enum.KeyCode.Space and gameprocess == false then
if holding then return end
holding = true
if not debounce then return end
debounce = false
script.Parent:FindFirstChild("Humanoid").JumpPower = 0
if script.Parent:FindFirstChild("BodyVelocity") then
return
end
local timehold = 0
local timer = runservice.Heartbeat:Connect(function(step)
if timehold <= maxtime then
timehold = timehold + 0.04
else
end
end)
if not input.KeyCode == Enum.KeyCode.Space and timehold < maxtime then
timer:Disconnect()
holding = false
debounce = true
timehold = 0
script.Parent:FindFirstChild("Humanoid").JumpPower = 50
script.Parent:FindFirstChild("Humanpid").Jump = true
end
spawn(function()
while true do
wait()
if timehold >= maxtime and holding == true then
timer:Disconnect()
timehold = 0
holding = false
debounce = true
local vel = Instance.new("BodyVelocity")
vel.Parent = script.Parent
vel.MaxForce = Vector3.new(math.huge, math.huge, math.huge)
vel.Velocity = Vector3.new(0,0,0)
end
end
end)
end
end)
What happens is when a player presses Spacebar, the character wont jump and after about 2 seconds receives bodyvelocity instead of checking if the player holds the spacebar for 2 seconds.

4 comments
"not input.KeyCode == Enum.KeyCode.Space" is NOT the same as "input.KeyCode ~= Enum.KeyCode.Space". Operator precedence.
Also why are you using a infinite loop? With such a short yield? Calling wait with an extremely small number or with no args at all is code smell, which is a flaw in your code which can result in a bigger problem.
1st of all i'm almost 100% sure "not input.KeyCode == Enum.KeyCode.Space" is exactly the same as "input.KeyCode
= Enum.KeyCode.Space" because "=" means X is not Y and with "not" also means X is not Y. 2nd of all what else should i use if not a loop"not input.KeyCode == Enum.KeyCode.Space" it first inverts the value of "input.KeyCode" to false , then compares it to "Enum.KeyCode.Space". The correct way would be either "not (input.KeyCode == Enum.KeyCode.Space)" or "input.KeyCode ~= Enum.KeyCode.Space"