Search Unity

RaycastHit.normal isn't correct?

Discussion in 'Physics' started by GuardHei, Jul 31, 2018.

  1. GuardHei

    GuardHei

    Joined:
    Feb 10, 2018
    Posts:
    89
    Basically I want to use SweepTest to check the potential collisions for the player movement. This is the code snippet I used.
    Code (CSharp):
    1. RaycastHit hitInfo;
    2.         float height = 0;
    3.         // sign here just shows whether it is to the left or to the right (-1/1)
    4.         if (_rigidbody.SweepTest(new Vector3(sign, 0, 0), out hitInfo, distance * sign, QueryTriggerInteraction.Ignore)) {
    5.             distance = hitInfo.point.x - transform.position.x - transform.localScale.x / 2;
    6.             Debug.Log(hitInfo.normal)
    7.             if (hitInfo.normal.y != 0f || hitInfo.normal.z != 0f) {
    8.                 Debug.Log("Adjust !");
    9.                 height = hitInfo.point.y + transform.localScale.y / 2 - transform.position.y;
    10.             }
    11.             Debug.DrawLine(hitInfo.point, hitInfo.point + 10 * hitInfo.normal, Color.red, 100, true);
    12.         }
    It is ok to ignore the second embedded `if else` structure here. However, something goes wrong here. I expect the script to print out the normal of the hit surface and draw a line of it. It is expected that when my player SweepTest a vertical wall, the normal is (1, 0, 0) or (-1, 0, 0) depends on front or back. The weird thing is, even the player SweepTest on a slope, the normal is still (-1, 0, 0) and the line drawn is a horizontal one.

    Here's the pics. (I have some post effects including grains, forgiveness for the terrible quality)
    This one is the slope my player is facing.


    This one is the scene view in 2d mode to show the normal line more clearly.


    I expect a line that points somewhat 60 degrees from the ground instead of a horizontal one. I've also check the mesh of the slope, well just two triangles, perfectly normal. So what's wrong?

    (Sorry for my poor english and appreciate for any help)
     
  2. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,770
    Can you get hit info name (s)?
    Could it be, that you hitting, or getting info from wrong object?
     
  3. GuardHei

    GuardHei

    Joined:
    Feb 10, 2018
    Posts:
    89
    Oh, yes! I just found that the player actually hit the block behind after debugging the name. I've tried to draw the line without depthtest which makes everything clear now.


    I think I get to know the answer now. Probably because my player "touches" on the slope before the SweepTest so SweepTest won't check any existing collisions.

    Thanks for your help!