Raycast2D for top-down game not working as expected
I am trying to create a top-down application where I need to check if a point lies on a particular type of square. I found the best way to do it was using RaycastHit2D hit = Physics2D.Raycast(from, -Vector2.up, 1.0f);
where from
is a Vector2
point.
However, this returns nothing when executed. I tried using Debug.DrawRay()
with the same parameters and I can see the white "dots" that represent the 2D rays.
My function is as follows:
int checkObstacle(Vector2 from){
RaycastHit2D hit = Physics2D.Raycast(from, -Vector2.up, 1.0f);
Debug.DrawRay(from, -Vector2.up, Color.white, 100.0f);
if(hit.collider != null){
if(hit.collider.tag == "Obstacles"){
return 0;
}else if(hit.collider.tag == "Walkable"){
return 1;
}
}
return -1;
}
Answer by Abhiroop-Tandon · Mar 24, 2016 at 09:51 AM
Try using
int checkObstacle(Vector2 from){
RaycastHit2D hit = Physics2D.Raycast(from, -Vector2.up, 1.0f);
Debug.DrawRay(from, -Vector2.up, Color.white, 100.0f);
if(hit.collider.gameObject.tag == "Obstacles"){
return 0;
}else if(hit.collider.gameObject.tag == "Walkable"){
return 1;
}
}
return -1;
}
Thanks a lot, I will try it out and get back if it doesn't work.
Well, I just tried it and it didn't work. No collisions are being detected.
And are you sure sure that all the objects are tagged correctly and everything else is fine ?? Just double check