user10823919
user10823919

Reputation:

Unity Rigidbody is sliding after jumping

I would like my character to jump diagonally but when it hits the ground it slides.

private void Update()
{
    if (Input.GetMouseButtonUp(0) && isGrounded())
    {
        //jump 
        timeHeld = 0;
        Debug.Log("MouseButtonUp = true");
        rb.AddForce(jumpDirection, ForceMode2D.Impulse);
    }
    else if (isGrounded())
    {
        rb.velocity = Vector2.zero;
    }
}

this code somehow works but it glitches when the player hits the ground. I need to put some amount of force to get him out of isGrounded() or he will just get some pixels up and be instantly pushed down again. This is my isGrounded() function

private bool isGrounded()
{
    RaycastHit2D raycastHit = Physics2D.BoxCast(boxCollider2d.bounds.center, boxCollider2d.bounds.size, 0f, Vector2.down, 0.1f, platformLayerMask);
    return raycastHit.collider != null;
}

the problem is obviously my distance which is 0.1f in Boxcast(). Any ideas how to fix that?

Upvotes: 2

Views: 953

Answers (1)

Arutyun Enfendzhyan
Arutyun Enfendzhyan

Reputation: 1909

No need to check the ground by yourself.

  1. Add a unity event called OnCollisionEnter
  2. Inside, check if the collider is the ground
  3. If true, then velocity = zero

Upvotes: 2

Related Questions