- Home /
Raycast2D hits itslf
Ok so I am probably just doing something wrong since the 2D physics is all new. But what I am trying to do is fairly simple. Run a raycast from a square with a Rigidbody2D and BoxColider2D attached. I am using the code:
//Trace Down
HitInfo = Physics2D.Raycast(transform.position, -transform.up, 1);
if(HitInfo.collider != null)
{
Debug.Log("HIT " + HitInfo.collider);
if(HitInfo.collider.GetComponent(Hull) != null)
{
NewLinks.Add(HitInfo.collider.GetComponent(Hull));
}
}
Problem is according to that log it is hitting itself. I can't use a mask because it is looking for other squares that are just like it so if it cant see itself it also would not be able to detect other like squares.
With a normal 3D raycast this wouldn't be a problem since the ray is originating inside the mesh faces and thus would not count the collision.
Any ideas?
Answer by robertbu · Feb 14, 2014 at 06:41 AM
A bit of a hack, but you can turn the collider off and back on for the current object around the Raycast2D:
collider2D.enabled = false;
HitInfo = Physics2D.Raycast(transform.position, -transform.up, 1);
collider2D.enabled = true;
That worked for me. Its kind of ugly though. It would be nice if the devs make ad an option or something so Raycast2D wont hit the object that they are being emitted from by default.
Again its less of a problem with 3D since collision is typically one sided, but 2D physics seem to work differently.
A more traditional approach would be @whydoitoit's solutions. I did not suggest RaycastAll() and RaycastAllNonAlloc() because I though the results did not guarantee order (i.e. they should be considered unsorted) like the ones from Physics.RaycastAll(), and the extra overhead of sorting made the solution a bit ugly. But according to what I just read in the reference for Physics2D.RaycastAll():
The colliders in the array are sorted in order of distance from the origin point.
So this might be a better approach. If the returned array has more than 1 item, then the item at index 1 will be your first hit.
Yeah and if you use the NonAlloc version you can pass a two element array, which is kind of nice.
Answer by whydoidoit · Feb 14, 2014 at 07:04 AM
You could use RaycastAll or RaycastAllNonAlloc to get all of the collisions of the ray or you could offset the start of your ray by the size of the existing collider.
Your answer
Follow this Question
Related Questions
How Physics2D.OverlapCircleAll works??? 1 Answer
Drag rigid body based on touch in 2D 0 Answers
how polygon collider 2d calculates center of mass? 2 Answers
Game not working on Tizen 0 Answers
LayerMask help 2 Answers