I created a small 2D sidescroller movement.
private Rigidbody2D rigid;
private BoxCollider2D playerCollider;
private bool isMovingRight = false;
private Vector2 movement;
private bool jumpPressed;
private const int MOVEMENT_SPEED = 5;
private const int JUMP_POWER = 5;
private const float GROUNDCHECK_TOLERANCE_SIDE = 0.05f;
private const float GROUNDCHECK_TOLERANCE_BOTTOM = 0.05f;
private void Start()
{
rigid = GetComponent<Rigidbody2D>();
playerCollider = GetComponent<BoxCollider2D>();
}
private void Update()
{
SetMovement();
}
private void FixedUpdate()
{
Move();
}
private void SetMovement()
{
float horizontalMovement = Input.GetAxis("horizontal") * MOVEMENT_SPEED;
if (Input.GetButtonDown("Jump"))
{
jumpPressed = true;
}
movement = new Vector2(horizontalMovement, rigid.velocity.y);
}
private void Move()
{
if (GroundCheck(true) || GroundCheck(false))
{
if (jumpPressed)
{
movement.y = JUMP_POWER;
jumpPressed = false;
}
}
rigid.velocity = movement;
}
private bool GroundCheck(bool checkLeftSide)
{
Bounds colliderBounds = playerCollider.bounds;
Vector2 rayPosition = colliderBounds.center;
float horizontalRayPosition = colliderBounds.extents.x + GROUNDCHECK_TOLERANCE_SIDE;
if (checkLeftSide)
{
rayPosition.x -= horizontalRayPosition;
}
else
{
rayPosition.x += horizontalRayPosition;
}
return Physics2D.Raycast(rayPosition, Vector2.down, (playerCollider.size.y / 2) + GROUNDCHECK_TOLERANCE_BOTTOM);
}
I register Inputs in Update and handle the Physics in FixedUpdate. When pressing the Jump Button the players jump works fine.
But when pressing jump multiple times, the player jumps up in the air, comes down and jumps one time again.
So if pressing the button more than 1 time the player will jump a second time after finishing the first jump.
How can I avoid this behaviour?
movement.y = JUMP_POWER;should probably bemovement.y += JUMP_POWER;jumpPressed = false.