Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Question Physics.Raycast hit distance <> vector distance

Discussion in 'Physics' started by Erenquin, Apr 10, 2021.

  1. Erenquin

    Erenquin

    Joined:
    Apr 9, 2018
    Posts:
    164
    Hello,
    have a question regarding Raycast hit distance.
    I orignally had an issue and found another thread mentioning we should normalize the direction vector.

    Without normalized direction I have values for hit.distance within the maxdistance value (for maxdistance 5, I had values like 4.7, 4.9, ...)
    With normalized direction I have values between 0 and 1.
    It is strange for me that the direction has such an influence on the distance.

    I suppose that if I multiply maxdistance by the normalized direction I will get the actual distance ?

    Additionally, in both cases, the object distance (calculated with Vector3.Distance), give values such as 22.8, 23.7 ...).
    So object distance has nothing to do with hit.distance.

    Why ?

    Code (CSharp):
    1.             if (Physics.Raycast(transform.position, Vector3.Normalize(SeenObject.transform.position - transform.position), out hit, SightRadius, WhatToPursuit))
    2.             {
    3.                     Debug.Log("vector distance " + Vector3.Distance(transform.position, SeenObject.transform.position - transform.position));
    4.                     Debug.Log("seenobject distance " + hit.distance);
    5.             }
     
    Last edited: Apr 10, 2021
  2. msh91

    msh91

    Joined:
    Apr 22, 2017
    Posts:
    40
    I'm not sure about the results you're seeing with the direction (although I am sure it should be normalized like you just showed), but regarding the distance to the object:

    You're checking the distance to the origin of the objects (usually the center).
    The raycast however will return the distance from the original point to the hit point. That is, the point of contact between the ray and the collision object.

    So it could make sense if your target object has a collision shape with distance from it's origin to the edge of it of about 18.
     
  3. Erenquin

    Erenquin

    Joined:
    Apr 9, 2018
    Posts:
    164
    Thanks for the answer.

    Well, well, well,
    that was totally stupid.

    I was actually using a direction vector instead of the position:
    Code (CSharp):
    1.  Vector3.Distance(transform.position, SeenObject.transform.position - transform.position)
    ->
    Code (CSharp):
    1. Vector3.Distance(transform.position, SeenObject.transform.position)
    The copy/paste devil striked.

    Still your answer helped as I did not think of the difference between "hit point" and the pivot.
     
    Last edited: Apr 12, 2021