Adding Jump Power based on how long the player has held down their jump button

How would I add jump power to a player if they hold down their jump key for x amount of seconds?

Here is an example, Player A holds down their jump key for 5 seconds. After 5 seconds, they release it, they jump, and their jump power gets multiplied by 1.5 since they held it down.

how would I do this?

I tried using the KeyPress hook and LocalPlayer():KeyDown(IN_JUMP) but it didnt work.

any help would be appreciated, thanks.

Same CurTime() to a variable when player presses jump button.
When they release the button, calculate the difference in time, do your calculations and apply the force.

So I tried this:



function JumpPowerTest(ply, key)
	if (!ply:KeyDown(IN_JUMP)) then
		return;
	end
	
	local starttime = nil;
	if (ply:KeyDown(IN_JUMP)) then
		starttime = CurTime();
	end
	
	if (ply:KeyReleased(IN_JUMP)) then
		local force = CurTime() - starttime;
		ply:SetJumpPower(ply:GetJumpPower() * force)	
	end
end
hook.Add("KeyPress", "JumpPowerTest", JumpPowerTest)


But for it doesn’t work, no errors.

Also, how would I make it so they don’t jump until they release the button, because currently, they jump when they press space.

You did not block the normal jumping. I am certain that this is somewhere implemented in your gamemode. Theorhetically you Need to disable it there. After that you could put your function there. You could even Name it the same like the old function, so addons that base on this function can still work etc.

No zmeja, the problem lies in what he’s doing along the way:


    if (!ply:KeyDown(IN_JUMP)) then
        return;
    end

If they aren’t holding the jump key the hook doesn’t run. This is a pretty good idea to isolate it to jumping only, but this next check becomes redundant because it won’t ever happen unless jump is pressed.


    local starttime = nil;
    if (ply:KeyDown(IN_JUMP)) then
        starttime = CurTime();
    end

You keep resetting the jump time as long as any key is pressed. It’s not tied to the player either so this won’t be of any use to you in the long run. And finally:


hook.Add( "KeyPress" )

This hook is only for when the key is pressed, not released. YOu need to use

GM/KeyRelease for the release part. Which is why you’ll see not tying the variable to the player is not going to work for you.