- Home /
Unity 2D: Variable Jump Height with a Double Jump
This problem has been driving me up the wall recently and I would love some advice. I am making a 2D platformer using physics based movement (I know there are better options available but I'm a beginner). I want my character to have variable jump height based off of how long they hold down the jump button. I also want them to be able to double jump in mid-air. I would further like for them to be able to jump once if they simply fall off a platform.
I have got the double jump and the variable jump height working separately, but cannot get them to work together.
// Jumping
bool isJumping;
[SerializeField] float jumpForce;
[SerializeField] float doubleJumpForce;
[SerializeField] int maxJumps;
[SerializeField] int jumpsLeft;
[SerializeField] float maxFallSpeed;
[SerializeField] bool isGrounded;
[SerializeField] Transform feetPos;
[SerializeField] float checkRadius;
[SerializeField] LayerMask whatIsGround;
private float jumpTimeCounter;
[SerializeField] float jumpTime;
void Update()
{
isGrounded = Physics2D.OverlapCircle(feetPos.position, checkRadius, whatIsGround);
moveInput = Input.GetAxisRaw("Horizontal");
if (Input.GetKeyDown(KeyCode.Space) && jumpsLeft > 0)
{
isJumping = true;
jumpsLeft--;
jumpTimeCounter = jumpTime;
}
}
private void FixedUpdate()
{
if (isJumping == true)
{
if (jumpsLeft == maxJumps)
{
if (jumpTimeCounter > 0)
{
jumpTimeCounter = jumpTime;
playerRB.velocity = new Vector2(playerRB.velocity.x, jumpForce);
}
}
}
else if (isGrounded == true)
{
jumpTimeCounter = jumpTime;
jumpsLeft = maxJumps;
}
if (Input.GetKey(KeyCode.Space) && isJumping == true)
{
if (jumpTimeCounter > 0)
{
playerRB.velocity = new Vector2(playerRB.velocity.x, jumpForce);
jumpTimeCounter -= Time.fixedDeltaTime;
}
else
{
isJumping = false;
}
}
if (Input.GetKeyUp(KeyCode.Space))
{
isJumping = false;
}
}
So far this actually works for a double jump, but I really want the double jump or the 'second jump' to have a lower jumpForce than the first one. I also don't know how to implement the double jump after falling.
I'm also having issues where sometimes my character just continues to fly upwards. It happens more often when I maximize the game in editor. Not sure what's going on.
Your answer
Follow this Question
Related Questions
isGrounded is always false, even with gravity, how do you fix that? 1 Answer
Why does this piece of code work with gravity and this one dosent 2 Answers
Rigidbody2D AddForce only working with large numbers 2 Answers
How to check if object is on ground (C#)? 1 Answer
Can't control movement while jumping 1 Answer