- Home /
Collision Detection If Raycast Source Is inside A Collider?
It seems that when you raycast 1 ray, if the origin point is inside the collider A, it won't able to detect collision with A. Is my observation correct?
If so, how to overcome it?
Answer by Bunny83 · Jun 14, 2011 at 01:52 AM
Yes this is right.
"Note: This function will return false if you cast a ray from inside a sphere to the outside; this in an intended behaviour."
See Physics.Raycast.
There is no general approach to circumvent this, it depends on what you want to achieve.
Answer by kimag · Sep 28, 2012 at 01:59 PM
You can reverse your ray:
ray.origin = ray.GetPoint(100);
ray.direction = -ray.direction;
Example from my project:
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
ray.origin = ray.GetPoint(100);
ray.direction = -ray.direction;
if (theCollider.Raycast (ray, hit, 100.0))
{
Debug.DrawLine (transform.position, hit.point, Color.red);
}
Reversing is very elegant and solved the same issue I was having.
The most elegant way to reverse a raycast inside a collider (sphere in my case). Thanks, you saved my day!
p.s I wanted to place a empty game object outside the collider an point the raycast in collider direction, but the reverse raycast method is brilliant!
Answer by computas · Apr 17, 2019 at 08:38 PM
Old question, but still first in google search. So here we go:
Unity now days have this option "Queries hit backfaces". It solved the problem for me. You can find it in "Edit/project setting/physics"
Answer by ShawnFeatherly · Jun 17, 2013 at 02:46 AM
I needed to do this as well. kimag got me going in the right direction, but I needed a bit more accuracy.
I only had to deal with one GameObject being able to collide with the rays. Which made this a bit easier. My method was to use kimag method to not only find the collision point in front of the line but also behind the line. This results in what could be thought of as a line segment parallel and along the rays direction that runs along the object being collided with. After you have this, the rays origin is checked to see if it's inside that line segment.
RaycastHit hit;
Ray rayForward = new Ray(origin, end3 - origin);
Ray rayBehind = new Ray(end3, origin - end3);
//find point in front of ray
rayBehind.origin = rayBehind.GetPoint(-100);
Physics.Raycast(rayBehind, out hit, 100f);
Vector3 beyondForward = hit.point;
//find point behind ray
rayForward.origin = rayForward.GetPoint(-100);
Physics.Raycast(rayForward, out hit, 100f);
Vector3 beyondBehind = hit.point;
//check if rays origin is between points
bool isRayInside =
origin.x > Mathf.Min(beyondForward.x, beyondBehind.x)
&& origin.x < Mathf.Max(beyondForward.x, beyondBehind.x)
&& origin.y > Mathf.Min(beyondForward.y, beyondBehind.y)
&& origin.y < Mathf.Max(beyondForward.y, beyondBehind.y);