- Home /
My raycast does not work as espected
I'm doing a 2D game, and i'm tryng to use raycast as a criteria for jump. but my raycast is returning the gameobject who called the raycast.
My code is like that
if (Input.GetKeyDown(KeyCode.Space))
{
RaycastHit2D hit = Physics2D.Raycast(transform.position,-Vector2.up,10f);
if (hit.collider != null )
{
rigidbody2D.AddForce(Vector3.up * 200);
}
}
if i put a print(hiy.collider.name); it returns the name of the gameobject who is casting it.
Yep. One solution is to turn the collider off before the Raycast and then turn it back on after. This seems hackish to me, but I have yet to see a better solution. If you know the size of your object, you could extend the start position beyond the edge of the collider.
Answer by ian_sorbello · Oct 07, 2014 at 05:34 AM
Try doing this
RaycastHit2D[] hits = Physics2D.RaycastAll(...);
foreach(RaycastHit2D hit in hits)
{
if(hit.collider.name != "me")
...
}
(replace "me" with your gameobject's name)
It won't be as performant, but at least enables you to dismiss the gameobjects own collider.
There is also the Physics2D.IgnoreCollision() call - take a look in the docs for how that works. It might be more difficuly with firing a ray - it might be specifically for two different colliders, I'm not sure.
Ian.
Its working. I dont feel like this is the correct solution, but still working. Thank you
Answer by tanuj0092 · Oct 07, 2014 at 05:41 AM
Hi,
Try to check that whether the rigid body you are trying to find with ray cast is already a child of another rigid body or not? If yes then It will return the parent rigidbody gameObject.