- Home /
Raycast 2D with origin inside the collider
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 ?
Answer by zomi1one · Oct 30, 2016 at 09:35 PM
go to edit -> Projekt Settings -> Physics2D -> uncheck Queries(Raycast) start in collider
Your answer
Follow this Question
Related Questions
Physics.Raycast not checking layermask properly? 1 Answer
Logic to detect objects entering between the player and camera? 1 Answer
Continuously moving rigidbody 2 Answers
BoxCollider vs. RaycastAll 1 Answer
Can't get a laser working properly. 2 Answers