I am running raycasts (2d) in a loop, where every iteration uses the hit point from previous iteration as it’s origin for the raycast.
Example code:
// Cast a ray
var hit = Physics2D.Raycast(currentPosition, currentDirection);
while (hit.collider)
{
// get new position
currentPosition = hit.point;
// get new direction
currentDirection = Vector3.Reflect(currentDirection, hit.normal);
// Calculate hit.
hit = Physics2D.Raycast(currentPosition, currentDirection);
}
This sometimes fails to work properly, and it seems to be related to the fact that the origin is inside the collider object.
The documentation also mentions this (taken from: Physics2D.Raycast )
Additionally, this will also detect
Collider(s) at the start of the ray.
In this case the ray is starting
inside the Collider and doesn’t
intersect the Collider surface. This
means that the collision normal cannot
be calculated in which case the
collision normal returned is set to
the inverse of the ray vector being
tested. This can easily be detected
because such results are always at a
RaycastHit2D fraction of zero.
My question is – what would be the easiest way to set the origin to the surface of the previous collider found, such that it will not suffer from this behavior ?