RaycastHit2D normal returns raycast in opposite direction, not surface normal.
What I'm trying to do is when a projectile in my game hits a surface, I want to spawn an impact effect along the surface. To do this, I figure I need the normal of the surface the projectile is colliding with. RaycastHit2D is supposed to provide this, so I raycasted from the projectile collision point to the surface it collided with, but after some odd results and ray drawing debugging, I noticed that the normal being returned was just the raycast reversed. After searching online, I stumbled onto the note in the docs that this is normal behaviour if the raycast begins inside a collider. I figured this was the issue, since I was starting the ray at the point of collision. But even when I move it away from the surface, it still gives me the same result. I've tried moving it away a variety of distances to no success.
My code for the raycasting is as follows:
//This is inside an OnCollisionEnter2D method
//transform.position is the position of the projectile, which will be at the point of collision.
//The projectile is rotated in the direction of travel, and since this is 2D, transform.right is
the "forward" vector.
Ray2D ray = new Ray2D(transform.position + -transform.right, transform.right);
RaycastHit2D collidedSurfaceHit = Physics2D.Raycast(ray.origin, ray.direction, Mathf.Infinity);
Debug.DrawRay(ray.origin, ray.direction * 5.0f, Color.blue, 10.0f); //Draw initial raycast
Debug.DrawRay(transform.position, collidedSurfaceHit.normal * 5.0f, Color.red, 10.0f); //Draw surface normal
float angleBetweenCollisionAndNormal = Vector2.Angle(transform.position, collidedSurfaceHit.normal);
A couple of images that demonstrate what I'm talking about:
The Initial Raycast:
The RaycastHit2D Normal:
Does anybody know what's going on here?
Answer by DEADTERMINATOR · Jun 22, 2017 at 08:37 PM
Feeding the exact layers I want to consider into the raycast seemed to fix it. I don't know what collider(s) the raycast was beginning inside of, but apparently there was something.