- Home /
hit.normal != Vector2.up evaluates to true even when hit normal is Vector2.up
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;
}
Answer by zenmasterchris · Apr 10, 2020 at 05:56 AM
I output the value of the hit normals using ToString("F8")
because it turns out (thanks to this thread) the normal ToString()
has low precision. The hit normal coming from the flat surface on the lower left is quite a bit further away from being exactly (0, 1) than the hit normal on the upper right flat surface.
Right. That's a general issue with floating point values. Just to actually provide a solution: If you want to check if a direction is about the same direction you can use the Dot product like this:
if (Vector3.Dot(hit.normal, Vector2.up) >= 0.99f)
or to have a better intuition for the threshold you can use Vector3.Angle
if (Vector3.Angle(hit.normal, Vector2.up) < 0.1f)
Your answer
Follow this Question
Related Questions
How to make my character stop stuttering when walking down a slope? 2 Answers
How to check if a raycasthit detects an angle less than 45 degrees and touches the ground 2 Answers
Having trouble with simple 2D movement 4 Answers
Preventing CharacterController sliding down edges on platforms, ground detection. 2 Answers