My player loses jump ability when moving left or right

Viewed 22

I have 2 problems. I'm trying to stop infinite jumps. However my player doesn't jump when the gizmo line is slightly sticking out. So I tried to increase the gizmo line and my player starts to jump when I make the gizmo line like 2000 but strangely you'd think my player would jump infinitely because the detection line is so long but he only jumps when he collides with the ground... and also my player loses the ability to jump when I move left or right. Something is really wrong and I hope you can help me. :)


    [Header("Components")]
    private Rigidbody2D rb;

    [Header("Layer Masks")]
    [SerializeField] private LayerMask groundLayer;

    [Header("Movement Variables")]
    [SerializeField] private float movementAccelaration;
    [SerializeField] private float maxMoveSpeed;
    [SerializeField] private float linearDrag;
    private float horDirection;
    private bool changingDir => (rb.velocity.x > 0f && horDirection < 0f) || (rb.velocity.x < 0f && horDirection > 0f);

    [Header("JumpVariables")]
    [SerializeField] private float jumpForce = 12f;
    private bool canJump => Input.GetButtonDown("Jump") && onGround;

    [Header("Collision Variables")]
    [SerializeField] private float groundRayCastLength;
    private bool onGround;


    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        horDirection = GetInput().x;
        if (canJump) Jump();

    }

    private void FixedUpdate()
    {
        CheckCollisions();
        MoveCharacter();
        ApplyLinearDrag();
             
    }







    private Vector2 GetInput()
    {
        return new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
    }

    private void MoveCharacter()
    {
        rb.AddForce(new Vector2(horDirection, 0f) * movementAccelaration);

        if (Mathf.Abs(rb.velocity.x) > maxMoveSpeed)
        {
            rb.velocity = new Vector2(Mathf.Sign(rb.velocity.x) * maxMoveSpeed, rb.velocity.y);
        }
    }

    private void ApplyLinearDrag()
    {
        if(Mathf.Abs(horDirection) < 0.4f || changingDir)
        {
            rb.drag = linearDrag;
        }
        else
        {
            rb.drag = 0f;
        }
    }

    private void Jump()
    {
        rb.velocity = new Vector2(rb.velocity.x, 0f);
        rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
    }

    private void CheckCollisions()
    {
        onGround = Physics2D.Raycast(transform.position * groundRayCastLength, Vector2.down, groundRayCastLength, groundLayer);
        
    }

    private void OnDrawGizmos()
    {
        Gizmos.color = Color.green;
        Gizmos.DrawLine(transform.position, transform.position + Vector3.down * groundRayCastLength);
    }

}


0 Answers
Related