I
I
Ilya Famin2021-05-02 07:00:54
C++ / C#
Ilya Famin, 2021-05-02 07:00:54

Why is jump not working in Unity 2D?

private float speed = 8;
    float jumpForce = 15;
    private bool isGround = false;

    private Rigidbody2D rb;
    private SpriteRenderer sprite; 

    private void FixedUpdate() {
        CheckGround();
    }
    private void Update(){
        if (Input.GetButton("Horizontal")) 
            Run();
        if (isGround && Input.GetButton("Jump")) {
            Jump();
            Debug.Log("Jump");
        }
    }

    private void Awake() {
        rb = GetComponent<Rigidbody2D>();
        sprite = GetComponentInChildren<SpriteRenderer>();
    }
    private void Jump() {
        rb.AddForce(transform.up * jumpForce);
    }
    private void CheckGround() {
        Collider2D[] collider = Physics2D.OverlapCircleAll(transform.position, 0.3f);
        isGround = collider.Length > 1;
        Debug.Log("CheckGround");
    }

The problem according to the debug results is in this line , the expression assigns the value false, although in theory it should be true isGround = collider.Length > 1

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
GavriKos, 2021-05-02
@GavriKos

And why does it have to be true? For me, this is not obvious - why if we touch more than 1 collider, then we are on the ground?

C
CHIDWI, 2021-05-02
@CHIDWI

A very strange way to check the ground. Why not use the built-in features of OnCollisionEnter/stay/exit and check them by tag or name?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question