-1

In my platformer, my player clamps onto the sides of tiles and hooks there. I want to remove this so the player can't clamp onto the sides of any tiles on my Tilemap.

In my movement script, I tried to add a Raycast that shoots downwards. I excepted it to work but instead it isn't letting me jump and is playing the falling animation which only occurs if my isGrounded variable is set to false. I am suspecting something is wrong with my Raycast.

Here is the code:

void OnCollisionEnter2D(Collision2D col)
    {
         RaycastHit hit;
        if (Physics.Raycast(transform.position, Vector3.down, out hit)) 
        {
            if (hit.collider.gameObject == floor) 
            {
                isGrounded = true;
            }
        }
  
    }

NOTE: the floor variable is the tilemap

2 Answers2

0

Firstly, you don't need a raycast in your OnCollisionEnter2D.

To check if Ground is below you make sure your tiles have a collider set.

Then, add a new tag and name it "Ground."

Assign the new tag to the tilemap.

Use the new tag to check if your collision has it.

void OnCollisionEnter2D(Collision2D col)
{
     if (col.gameObject.CompareTag("Ground")
         isGrounded = true;
}

Secondly, if you don't want the first method, in 2D physics, you'd use Physics2D.RayCast > see reference <

RaycastHit2D hit = Physics2D.Raycast(transform.position, -Vector2.up);

if (hit != null) {
    // ...
}
Phillip Zoghbi
  • 512
  • 3
  • 15
0

You are using a 3D raycast. It should be physics2D. Reference Raycast 2D Code. Add a debug log statement to check if the raycast is executed. Also you are raycasting to an infinite length. Restrict it to say 1 unit below the player.

You can check out this video on how to ground check in a proper way.

Vionix
  • 570
  • 3
  • 8