If statement continues to repeat itself and runservice not stopping

I’m making a flying system but when timesPressed equals 3 it suppose to stop the runservice from continuing and disable the LinearVelocity
but it does the opposite(this problem only happens once)

a
wait(2)
local plr = game:GetService("Players").LocalPlayer
local char = plr.Character or plr.CharacterAdded:Wait()
local hum = char:WaitForChild("Humanoid")
local jumpMode = 0
local jumped = tick()
local flying = false
local hovering = false
local UIS = game:GetService("UserInputService")
local cam = workspace.CurrentCamera
local timesPressed = 0
local Connection
local flyVel = Instance.new("LinearVelocity")
flyVel.Enabled = false
flyVel.Parent = char:WaitForChild("HumanoidRootPart")
flyVel.MaxForce = math.huge
flyVel.Attachment0 = char.HumanoidRootPart.RootAttachment
flyVel.VelocityConstraintMode = Enum.VelocityConstraintMode.Vector
-- add orientation so player looks at camera so it can go up and down also
local hoverVel = Instance.new("LinearVelocity")
hoverVel.Enabled = false
hoverVel.Parent = char.HumanoidRootPart
hoverVel.MaxForce = math.huge
hoverVel.Attachment0 = char.HumanoidRootPart.RootAttachment
hoverVel.VelocityConstraintMode = Enum.VelocityConstraintMode.Vector
hoverVel.VectorVelocity = Vector3.new(0,0,0)

local function Flying()
	

	Connection = game:GetService("RunService").Heartbeat:Connect(function()
		if not flying then
			Connection:Disconnect()
		end
		if hum.MoveDirection == Vector3.new(0,0,0) then
			flyVel.Enabled = false
		else
			flyVel.Enabled = true
			flyVel.VectorVelocity = hum.MoveDirection * 30
		end
	end)
	
end

-- ... (rest of the code remains the same)



UIS.InputBegan:Connect(function(key,pro)
	if not pro then
		if key.KeyCode == Enum.KeyCode.Space then
			timesPressed+= 1
			if timesPressed > 3 then
				timesPressed = 3
			end
			if jumpMode == 0 then
				jumpMode+=1
			else
				if tick() - jumped < 1 then
					jumpMode+=1
					if jumpMode > 2 then
						jumpMode = 2
					end
				elseif tick() - jumped > 1 then
					jumpMode = 0 timesPressed = 0 hovering = false flying = false
				end
			end
			if jumpMode == 2 and hovering == false and flying == false then
				print("Hover") hovering = true
				hoverVel.Enabled = true
				
				if not Connection then
					task.spawn(Flying)
					flying = true
				end
			end
			jumped = tick()
			if hovering or flying then
				if jumpMode == 2 and timesPressed == 3 and hum.FloorMaterial == Enum.Material.Air then
					print("test")
					hovering = false flying = false jumpMode = 0 timesPressed = 0 Connection:Disconnect()
					flyVel.Enabled = false 
					hoverVel.Enabled = false
					print("Let go")
				end 
			end
		end
	end
end)

video: (https://gyazo.com/0423ef397603fda61b01c313011a102f)

oh, nevermind i fixed it with a simple variable

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