RaycastHit2D returns incorrect results when magnitude is 0

I’m using raycasting for player movement. I send out a ray and record the normal of the surface it collides with to determine how to translate the player. This works just fine until the player is a distance of 0 away from the wall. Then the raycasthit normal property returns the negative unit vector in the direction the ray was traveling, instead of the normal of the surface it hit. I assume the math for calculating the surface normal is unable to handle the raycast’s magnitude being 0?

Is there a way around this? Am I missing something?

EDIT: sketch in the comments

This is actually because of how a Vector works. The magnitude is the length of the vector so if it is 0 then the Vector essentially doesn’t exist and will give you some pretty weird results. The fix is to put a guard clause in front of the raycast if statement:

void Update() 
    if (rayVector.magnitude == 0) return; // becuase it would already be there

    if (Raycast)
        // Move Player

Hope this helps :slight_smile:

Well, the problem is that I do still need the normal of the collider. Here’s a little sketch of the problem that will hopefully make it more clear.


The orange player collider shoots out multiple raycasts in the direction of movement, in this case to the right, and then we select the shortest ray (red).

Then we look at the normal vector of the surface the ray collided with (purple). We can use this along with the desired movement vector (dotted red) to calculate how far up any slopes we find we should displace the player (blue).

My vectors in this sketch are drawn waaay longer than to scale just so it’s easier to read what I’m doing.

The problem is that, apparently, we cannot get the surface normal of the wall we’ve collided with from any raycast that is a distance of 0 from the wall.

At this point I do have some ideas, such as firing the rays from slightly inside of the player’s collider which adds some annoyance to the math but might work. Ideally though, it would turn out that there is another function I could use, or that I’m wrong about 0 length raycasts not working or something