Hello there I’m struggling with creating a cooldown for my jump on my 2D game, i’m writing in C# .
I’m wondering if anybody can tell me why when I add whats in my void update() section it stops me from jumping all together, but when I put the public void Jump() block in the void update() section by itself it allows me to jump, however as there’s no cooldown it can be repeatedly pressed until the character leaves the screen. Any help appreciated.
using UnityEngine;
using System.Collections;
public class JumpScript : MonoBehaviour {
Animator anim;
public float jumpSpeed = 1000F;
public float jumpTime;
public float jumpRate;
void Start()
{
jumpRate = 0.5f;
jumpTime = 0;
anim = GetComponent<Animator>();
}
void Update()
{
if(jumpTime > 0)
jumpTime -= Time.deltaTime;
if(jumpTime < 0)
jumpTime = 0;
if(jumpTime == 0)
{
Jump();
jumpTime = jumpRate;
}
}
public void Jump ()
{
if(Input.GetKeyDown(KeyCode.B))
{
rigidbody2D.AddForce(new Vector2(0, jumpSpeed));
anim.Play("Jumping");
}
}
}
Can you tell us what’s wrong with leaving it as it is? Having a discrete method for actions like jumping is a good idea. Also typically to be allowed to jump an “isGrounded” check exists to ensure the player isn’t in midair.
A coroutine would be useful here. Good idea to learn to use them early on!
you should not put an “If (Input.GetKey)” in a function. The way you put it actually would require you to press “B” exactly in the frame that launches the Jump() function. So one frame every 0.5 seconds. So almost impossible.
Instead, after a cooldown of 0.5 seconds, turn on a boolean to true like this:
using UnityEngine;
using System.Collections;
public class JumpScript : MonoBehaviour {
Animator anim;
public float jumpSpeed = 1000F;
public float jumpTime;
public float jumpRate;
public float jumpAllowed = false;
void Start()
{
jumpRate = 0.5f;
jumpTime = 0;
anim = GetComponent<Animator>();
}
void Update()
{
if(jumpTime > 0)
jumpTime -= Time.deltaTime;
if(jumpTime < 0)
jumpTime = 0;
if(jumpTime == 0)
{
jumpAllowed = true;
}
if(Input.GetKeyDown(KeyCode.B) && jumpAllowed)
{
rigidbody2D.AddForce(new Vector2(0, jumpSpeed));
anim.Play("Jumping");
jumpTime = jumpRate;
jumpAllowed = false;
}
}
Like this, only IF you jumped, you turn on this boolean (jumpAllowed) to false, and you set your jumpTime back to .5