- Home /
Unity Physics2D.Raycast always returns “the invoker” as hit
I'm trying to use Physics2D.Raycast in order to check if the player is on the ground (I know that there are other approaches to check if the player is on the ground but I think that the raycast is the most reliable). The problem is that in my scenario it returns the player itself as hit and I really don't understand why and what should I do. My code (in PlayerController) is the following:
public bool IsGrounded () {
Bounds bounds = this.playerCollider.bounds;
Vector3 rayOrigin = bounds.center;
rayOrigin.y -= bounds.extents.y;
RaycastHit2D hit = Physics2D.Raycast (rayOrigin, Vector2.down, 0.1f);
if (hit.collider != null) {
Debug.Log ("Collider is: " + hit.collider.name);
}
return hit.collider != null;
}
And I can debug the casted ray using:
Debug.DrawLine (rayOrigin, new Vector3 (rayOrigin.x, rayOrigin.y - 0.1f, rayOrigin.z), Color.magenta);
...and it gets casted as expected, while the Debug.Log always reports "Player" which is itself and I don't know how it's possible. So what's wrong?
ps. I'm using Unity 5.3
Answer by Cherno · Jul 06, 2016 at 09:51 PM
Simplest solution is to pass a LayerMask to the raycast that excludes the layer that the player is in.
Another more complex solution is to use RayCastAll, then sort the array of RayCastHits by distance, and then loop through the array, ingoring any hit that is the player object, and stopping once the first "real" hit is reached.
Answer by milanow · Jul 06, 2016 at 10:12 PM
The problem is that the ray always hits the player since you set the ray's startPoint as bound's center. Which is to say ray's start point "hits" the player's collision box first. And hit.collider always return the first object it hits. That's why you can never access to the "ground" object.
Cherno's answer is the best, you can change the layermask of the ray to cast ray on different layer. Simply separate player and ground to different layers and cast ray on ground's layer. Or as he said using raycastAll.
And a little tricky answer is moving the ray's original start point a little bit far from the bound (like a yOffest = 0.1f).
Your answer
Follow this Question
Related Questions
Layer Mask on raycast2d not working? 1 Answer
Raycast2D will point right, but won't point left when player turns. 1 Answer
2D Raycast effect only what it hits? 2 Answers
Raycast for a 2D objects 0 Answers