- Home /
Physics2D Raycast stops detecting collision
I'm trying to use Raycasting in a 2D project for jumping. It works fine if I jump once, wait for the player to fall and jump again, but if I hold the jump button the player jump 2 times and then when it touches the ground again it doesn't detect that collision, so the player can't jump anymore since the "canJump" variable depends on that collision, it also doesn't detect it if I jump to another cube that also has the "Floor" tag, and it should make the jump variable true as well.
Edit: I just noticed that just before this happens, it detects 2 collisions (the player just hits the ground once), that happens once or twice and then it just stops detecting them.
Here's the code for jumping:
height = gameObject.GetComponent<BoxCollider2D> ().size.y;
RaycastHit2D hit = Physics2D.Raycast (new Vector2(transform.position.x,transform.position.y-(height/2)-0.001f), Vector2.down, 0.04f);
if (hit.collider.tag == "Floor") {
canJump = true;
}
if (Input.GetAxis ("Jump") > 0 && canMove && canJump) {
rb.velocity = new Vector2 (
rb.velocity.x,
jumpForce
);
canJump = false;
}
Try to put first if statement below 2nd if statement. $$anonymous$$ight help.
Now I can jump more than 2 times by holding space , but if I keep holding it it stops jumping again at some point. And I still can't jump to another platform even if it has the same "Floor" tag, because if I do it won't detect the collision and I won't be able to jump again even if I go back to the first platform
Found this Q&A, its shows a solid way to check collision before jump. see if its helps you:
https://answers.unity.com/questions/196381/how-do-i-check-if-my-rigidbody-player-is-grounded.html