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?
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?
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);
}
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”
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.
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);