Search Unity

Help with Raycasting

Discussion in '2D' started by masterlewis05, Aug 11, 2019.

  1. masterlewis05

    masterlewis05

    Joined:
    Jan 16, 2016
    Posts:
    8
    Hey, how do I let my raycast's continue until they are outside of the collider so I can get the back-end coordinates instead? I drew this picture in paint so you know what I'm on about:
    Raycast.png
    Thanks
     
  2. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,807
    Not sure if there's another method, but once you detect the raycast hit, you could send another raycast from the opposite side/direction that only hits the originally hit collider.

    Untested code, but this could do it:
    Code (CSharp):
    1. // do the initial raycast
    2. RaycastHit2D hit = Physics2D.Raycast(origin, direction, float.MaxValue, hittableLayers);
    3.  
    4. // if it hit something
    5. if(hit.collider != null) {
    6.     // add twice the distance from the starting point to the hit
    7.     // which is a point on the other side of the object
    8.     Vector3 newOrigin = origin + (direction * hit.distance * 2);
    9.  
    10.     // raycast from the back
    11.     hit.collider.Raycast(newOrigin, -direction, float.MaxValue);
    12. }
    Depending on how complex your shape its, this may not give the true internal collision result you're looking for, but for convex shapes this should be able to do it.
     
    Last edited: Aug 12, 2019