I'm trying to make my character be able to jump once while in the air/double jump in a 2D Unity project and below is my code for it. The player character can jump once but just not again when in the air, though I think it is actually working in the program's eyes, because the jumpCounter variable does increase to 1 sometimes, but mainly straight to 2, so I think it's something to do with the space key being pressed multiple times in a frame even though I'm only pressing it once?
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController2D : MonoBehaviour
{
float xMovement = 0;
float jumpValue = 0;
Vector2 targetVelocity = new Vector2(0, 0);
Rigidbody2D myRigidBody;
public bool isGrounded = true;
public int jumpCounter = 0;
// Start is called before the first frame update
void Start()
{
myRigidBody = GetComponent<Rigidbody2D>();
myRigidBody.gravityScale = 8;
//myRigidBody.simulated = false;
}
// Update is called once per frame
void Update()
{
}
void checkInputs()
{
xMovement = Input.GetAxis("Horizontal");
jumpValue = 0;
if (isGrounded)
{
jumpValue = Input.GetAxis("Jump");
if (jumpValue > 0)
{
jumpCounter += 1;
}
if (jumpCounter >= 2)
isGrounded = false;
}
}
private void FixedUpdate()
{
checkInputs();
myRigidBody.velocity = new Vector2(xMovement * 20, myRigidBody.velocity.y);
myRigidBody.velocity = new Vector2(myRigidBody.velocity.x, jumpValue * 20);
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.transform.CompareTag("Ground"))
{
isGrounded = true;
jumpCounter = 0;
}
}
}