My issue is that the player sometimes (occasionally) doesn’t jump up while moving. It sometimes works, sometimes don’t. It’s weird, here’s the code:
[SerializeField] private LayerMask platformsLayerMask;
public Rigidbody2D rb;
public float MovementSpeed = 100f;
public float JumpingHeight = 100f;
public BoxCollider2D bc;
public float fallMultiplier = 2.5f;
public float lowJumpMultiplier = 2f;
void Awake()
{
rb = transform.GetComponent<Rigidbody2D>();
bc = transform.GetComponent<BoxCollider2D>();
}
void FixedUpdate()
{
if (IsGrounded() && Input.GetKeyDown(KeyCode.Space))
{
rb.velocity = new Vector2(rb.velocity.x, JumpingHeight * Time.deltaTime);
Debug.Log("Jumping");
}
HandleMovement();
}
private bool IsGrounded()
{
RaycastHit2D raycastHit2d = Physics2D.BoxCast(bc.bounds.center, bc.bounds.size, 0f, Vector2.down, 1f, platformsLayerMask);
Debug.Log(raycastHit2d.collider);
return raycastHit2d.collider != null;
}
void HandleMovement()
{
if (Input.GetKey(KeyCode.A))
{
rb.velocity = new Vector2(-MovementSpeed * Time.deltaTime, rb.velocity.y);
Debug.Log("Going Left");
}
else
{
if (Input.GetKey(KeyCode.D))
{
rb.velocity = new Vector2(+MovementSpeed * Time.deltaTime, rb.velocity.y);
Debug.Log("Going Right");
}
else
{
//no keys pressed
rb.velocity = new Vector2(0, rb.velocity.y);
Debug.Log("No key pressed");
}
}
if (rb.velocity.y < 0) //reponsive jumping and falling
{
rb.velocity += Vector2.up * Physics2D.gravity.y * (fallMultiplier - 1) * Time.deltaTime;
}
else if (rb.velocity.y > 0 && Input.GetKeyDown(KeyCode.Space))
{
rb.velocity += Vector2.up * Physics2D.gravity.y * (lowJumpMultiplier - 1) * Time.deltaTime;
}
}
}