- Home /
Prevent Jump Spamming
Hi! I’m working on a code that prevents the player spamming Jump, I came up with a script that should do just what I want but it seems that it works only every second time?? Note that in my game the jumps can differ in length, height and duration, that’s why I went with this approach. I would appreciate any help with my code or even ideas for a better one. Thanks!
//jumping based on current speed
if (controller.Grounded == true && Input.GetAxisRaw("Vertical") > 0 && afterjump == false)
{
player.AddForce(new Vector2(player.velocity.x - player.velocity.x * jumpdistance, jumpheight), ForceMode2D.Impulse);
Invoke("afterJumpFunction", 0.01f);
}
//finding time spot when player lands after jump
if (controller.Grounded == true && afterjump == true)
{
Invoke("jumpWait", jumpwait);
}
}
// Custom functions
void afterJumpFunction()
{
afterjump = true;
}
void jumpWait()
{
afterjump = false;
}
Note: jumpwait is just a float I’m setting in the inspector.
you could try if player.velocity.y < .1f then you can only jump if you are not moving up or down.. not sure if that will cause issues or not.
Answer by FlippyPls · Nov 13, 2021 at 06:00 PM
Idk if this'll solve the issue but I'd suggest doing something like
private void Update()
{
if (controller.Grounded == true && Input.GetAxisRaw("Vertical") > 0 && canJump)
{
player.AddForce(new Vector2(player.velocity.x - player.velocity.x * jumpdistance, jumpheight), ForceMode2D.Impulse);
StartCoroutine(JumpDelay());
}
}
IEnumerator JumpDelay()
{
canJump = false;
yield return new WaitForSeconds(jumpwait);
canJump = true;
}
This will create a "jumpwait" delay from the moment you do a successful jump and since you can't jump when you're not grounded you'll only be able to jump once you land again. You probably don't want to create any delays blocking input once the user has landed on the ground.
Your answer

Follow this Question
Related Questions
Spam jumping. 1 Answer
2D Double Jump problem 1 Answer
2d jumping, addForce hitting a max height despite force strength 2 Answers
Making a simple 2-D Jump script 0 Answers
Jump Down and Roll 1 Answer