Search Unity

Issue when trying to get the normal vector of the surface hit by a raycast

Discussion in 'Physics' started by niuage, May 22, 2020.

  1. niuage

    niuage

    Joined:
    Nov 17, 2019
    Posts:
    123
    I want a projectile that I'm moving by updating its position (dont want to use physics here) to bounce off a wall.

    So what I'm doing is detecting the collision, then using a raycast to get the normal of the wall, and then using vector3.reflect to know the new direction. As far as I know, I can't use the collision normal, as it's the normal of the object, and not the wall, right?

    The issue is that the normals are pointing up, instead of away from the wall (red lines).

    The code looks something like that:

    Code (CSharp):
    1.         point = collision.contacts[0].point;
    2.         dir = bullet.transform.forward;
    3.         point -= dir; // to step back a bit, for the raycast
    4.  
    5.         // this raycast is represented by the blue gizmo lines in the image below
    6.         if (Physics.Raycast(point, dir, out RaycastHit hitInfo, 10f, ~LayerMask.GetMask("EnemyBullet", "PlayerBullet"))) {
    7.  
    8.             // this is the collider surface normal
    9.             // it's represented by the red lines in the image below
    10.             var normal = hitInfo.normal;
    11.  
    12.             // this part is not important, what matters is finding out why the normal above is going up, and not away from the wall.
    13.             Vector3 reflect = Vector3.Reflect(-bullet.transform.forward, normal).Y(bullet.transform.position.y);
    14.             Debug.Log(reflect);
    15.             return reflect;
    16.         }
    17.  
    18.         return Vector3.zero;

    (zoomed in version of the raycast and normal here: https://i.imgur.com/TBSy4vb.png?1)

    And here's a video of the issue:


    - the white Gizmo line is the normal of the wall, obtained from raycast from the player towards the wall. It was meant as a reference, a debug tool. As you can see, it's in the correct direction

    - the blue lines are meant to represent the raycasts I do from the code above (`Physics.Raycast(point, dir`). They seem to go through the wall just fine.

    - Now the issue: the red lines are the normals I get from `var normal = hitInfo.normal;` in the code above. I would have expected them to be in the same direction as the white gizmo line...

    Can you see an obvious mistake in the above code? If you need more info, just ask.