I’m trying to detect flat ground vs slopes in my 2D platformer. As a first pass I’m doing a Raycast2D but for one of my flat surfaces my code is registering a slope when the hit normal from the ray cast is returning the up vector! The upper flat part of the tilemap registers correctly, the slope also registers correctly, but the bottom left flat ground registers as a slope with a normal vector pointed up (see my debug log output in the attached screenshot)!
Here’s my code:
private bool IsGrounded()
{
float extraHeight = 0.6f;
RaycastHit2D hit = Physics2D.Raycast(collider.bounds.center, Vector2.down, collider.bounds.extents.y + extraHeight, platformLayerMask);
Debug.Log(hit.collider);
Color rayColor = Color.red;
if (hit.collider != null && hit.normal == Vector2.up)
{
Debug.Log("FLAT GROUND! hit.normal = " + hit.normal);
rayColor = Color.green;
}
if (hit.collider != null && hit.normal != Vector2.up)
{
Debug.Log("SLOPE! hit.normal = " + hit.normal);
rayColor = Color.blue;
}
Debug.DrawRay(hit.point, hit.normal, Color.white, 5.0f);
Debug.DrawRay(collider.bounds.center, Vector2.down * (collider.bounds.extents.y + extraHeight), rayColor);
return hit.collider != null;
}