Double Jump Script Issues

So I have a double jump script and there is just a really small bug but it bothers me a lot. So whenever you load in the game the first jump you do, for some reason, is always the double jump. It functions normally after that but the very first jump the player performs is the double jump. Just curious if anyone can figure out why by looking through my script. Thanks!

Here’s the script:

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

local player = Players.LocalPlayer
local Character = player.Character or player.CharacterAdded:Wait()
local Humanoid = Character:WaitForChild("Humanoid")

type Animator = Animator & {
	LoadAnimation: (self: Animator, animation: Animation) -> AnimationTrack,
}

type AnimationTrack = AnimationTrack & {
	Play: (self: AnimationTrack) -> nil,
	Stop: (self: AnimationTrack) -> nil,
	IsPlaying: boolean,
}

local CanDoubleJump: boolean = true
local CanSetCanDoubleJumpToTrue: boolean = false
local DoubleJumpAnimation: AnimationTrack? = nil
local Animator: Animator? = nil

local function loadDoubleJumpAnimation(): AnimationTrack
	if not DoubleJumpAnimation then
		Animator = Humanoid:FindFirstChild("Animator") or Instance.new("Animator", Humanoid)
		DoubleJumpAnimation = Animator:LoadAnimation(script.Flip)
	end
	return DoubleJumpAnimation
end

local function handleJumpRequest()
	if CanDoubleJump then
		Humanoid.JumpPower = Humanoid.JumpPower * 1
		Humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
		local animation = loadDoubleJumpAnimation()
		animation:Play()
		CanDoubleJump = false
	end
end

local function handleStateChange(oldState: Enum.HumanoidStateType, newState: Enum.HumanoidStateType)
	if newState == Enum.HumanoidStateType.Landed then
		CanDoubleJump = false
		CanSetCanDoubleJumpToTrue = true
		Humanoid.JumpPower = StarterPlayer.CharacterJumpPower
		if DoubleJumpAnimation and DoubleJumpAnimation.IsPlaying then
			DoubleJumpAnimation:Stop()
		end
	elseif newState == Enum.HumanoidStateType.Freefall then
		if CanSetCanDoubleJumpToTrue then
			task.wait(0.2)
			CanDoubleJump = true
			CanSetCanDoubleJumpToTrue = false
		end
	end
end

local function onJumpRequestError(err)
	warn("Error in handleJumpRequest: " .. tostring(err))
end

local function onStateChangeError(err)
	warn("Error in handleStateChange: " .. tostring(err))
end

UIS.JumpRequest:Connect(function()
	local success, err = pcall(handleJumpRequest)
	if not success then
		onJumpRequestError(err)
	end
end)

Humanoid.StateChanged:Connect(function(oldState, newState)
	local success, err = pcall(handleStateChange, oldState, newState)
	if not success then
		onStateChangeError(err)
	end
end)

Again, thanks!

1 Like