So in my game I want the player to have the ability to jump while in the air multiple times, and have the time between the jumps increase the more they do it before eventually stopping. I’m very new to C#, and I haven’t been able to adapt any solutions online onto the code I’m using. I’m specifically coding in a 2d game environment. If anyone could help me here I would greatly appreciate it!
My movement script is bellow:
public class PlayerMovement : MonoBehaviour
{
private Rigidbody2D rb;
private void Start()
{
Debug.Log("Waddup Bitch");
rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
float dirX = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(dirX * 4f, rb.velocity.y);
if (Input.GetKeyDown("up"))
{
rb.velocity = new Vector2(rb.velocity.x, 7f);
}
}
}
OK - not a quick answer!. Here’s some code:
using System.Collections;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
bool canJump;
float jumpDelay;
Rigidbody2D rb;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
}
private void Start()
{
ResetJump();
}
private void Update()
{
float dirX = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(dirX * 4f, rb.velocity.y);
if (Input.GetKeyDown("up") && canJump)
{
canJump = false;
rb.velocity = new Vector2(rb.velocity.x, 7f);
StartCoroutine(Delay());
}
}
private void OnCollisionEnter2D(Collision collision)
{
if (collision.gameObject.CompareTag("Ground"))
ResetJump();
}
void ResetJump()
{
canJump = true;
jumpDelay = 0;
}
IEnumerator Delay()
{
jumpDelay++;
yield return new WaitForSeconds(jumpDelay);
canJump = true;
}
}
Firstly, Create a Tag of Ground and put that on your ground GameObject(s).
The principle of this is that there is a Boolean called canJump. You’re only allowed to jump when that is true. As soon as you jump, it is set to false and there is a delay of jumpDelay until it is turned back on again. To manage the delay, there is a Coroutine which delays for jumpDelay seconds and which also increments the delayTime by one second every time it is called.
If you land on the ground, you are able to jump again immediately and the jumpDelay is set back to zero.
Let us know how you get on!