I’m working on a little 2d platformer game and i can’t figure out why the player can continue jumping when he’s under a collision with the same tag as the ground.
Here is the player collision and movement code:
private int playerSpeed = 10;
private int playerJumpHeight = 1000;
private int playerDoubleJumpHeight = 800;
private float moveX;
public bool Grounded;
public bool doublejump = false;
private int jumps;
public float distancetoground = 0.9f;
void Update () {
PlayerMove();
}
void PlayerMove()
{
//Controls
moveX = Input.GetAxis("Horizontal");
if (Input.GetButtonDown("Jump") && Grounded == true && doublejump == false)
{
Jump();
jumps++;
}
else
{
if (Input.GetButtonDown("Jump") && doublejump == true)
{
DoubleJump();
jumps++;
}
}
//Animation
if (moveX != 0)
{
GetComponent<Animator>().SetBool("isRunning", true);
}
else
{
GetComponent<Animator>().SetBool("isRunning", false);
}
if (Grounded == false)
{
GetComponent<Animator>().SetBool("isJumping", true);
}
else
{
GetComponent<Animator>().SetBool("isJumping", false);
}
if (jumps == 2)
{
GetComponent<Animator>().SetBool("DoubleJump", true);
}
else
{
GetComponent<Animator>().SetBool("DoubleJump", false);
}
//Player direction
if (moveX < 0.0f)
{
GetComponent<SpriteRenderer>().flipX = true;
}
else if (moveX >0.0f)
{
GetComponent<SpriteRenderer>().flipX = false;
}
//Physics
gameObject.GetComponent<Rigidbody2D>().velocity = new Vector2(moveX * playerSpeed, gameObject.GetComponent<Rigidbody2D>().velocity.y);
}
void Jump()
{
//Jump code
doublejump = true;
Grounded = false;
gameObject.GetComponent<Rigidbody2D>().velocity = new Vector2(gameObject.GetComponent<Rigidbody2D>().velocity.x, 0);
GetComponent<Rigidbody2D>().AddForce(Vector2.up * playerJumpHeight);
}
void DoubleJump ()
{
//Double jump code
Grounded = false;
doublejump = false;
gameObject.GetComponent<Rigidbody2D>().velocity = new Vector2(gameObject.GetComponent<Rigidbody2D>().velocity.x, 0);
GetComponent<Rigidbody2D>().AddForce(Vector2.up * playerDoubleJumpHeight);
}
private void OnCollisionEnter2D(Collision2D col)
{
//Ground check
RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.down);
if (hit.collider != null && hit.distance < distancetoground && hit.transform.tag != "Ground")
{
Grounded = true;
jumps = 0;
doublejump = false;
}
}
}
And here is what the infinite jumping looks like:
In both cases i mashed the spacebar after jumping.
I should also include that both the ground and the blocks have the same “Ground” tag because they’re part of the same tilemap.