Search Unity

  1. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice
  2. Ever participated in one our Game Jams? Want pointers on your project? Our Evangelists will be available on Friday to give feedback. Come share your games with us!
    Dismiss Notice

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,768
    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
unityunity