0
\$\begingroup\$

I've got a player firing out 2d raycasts. If one of them hits a boxcollider2d I would like to know if it hit the top side, bottom side, left side, or right side. How would I go about doing this? I've tried using Bounds but that didn't work out very well.

\$\endgroup\$
3
  • \$\begingroup\$ pretty easy to do; Do your boxes rotate at all, or do they have a fixed rotation? \$\endgroup\$
    – Gnemlock
    Sep 6 '16 at 10:07
  • \$\begingroup\$ @Gnemlock They never rotate \$\endgroup\$
    – user61929
    Sep 6 '16 at 10:11
  • 1
    \$\begingroup\$ I do not want to post an answer I can not double check, and don't have the time to test at present. You could try checking hit.normal (I am not sure if this is applicable in 2D), you could check hit.point against hit.transform, you could compare the transforms of the collider and the object initiating the raycast; I'm also sure there would be more advanced ways that would be more efficient. \$\endgroup\$
    – Gnemlock
    Sep 6 '16 at 10:35
0
\$\begingroup\$

Compare contact point with bounds of your collider. You can get center and extents of collider to get coordinates of each side of collider, and see, which side contact point belongs to.

See image below for example.

enter image description here

Red line is raycast line, green square - collider. You can get contact point from RaycastHit2D. Then simply check: if contact point X coordinate is equal to bound center.X + extents.X - it is either corner or right side. Same goes for left side - contact point X will be equal to center.X - extents.X. For upper and lower check you just should change X to Y.

Also, don't forget, that it is possible for raycast to hit corner - X and Y of contact point in such situation will be equal to both center.X +- extents.X and center.Y +- extents.Y correspondingly.

For more details, see Bounds reference.

\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy