- Home /
Physics.Raycast doesn't hit anything even though Debug.DrawRay works
I'm trying to figure out if a player is on top of any platform tiles, which are made in the script from prefabs.
bool isGrounded(){
Debug.DrawRay (transform.position, -Vector3.up * (collider2D.bounds.size.y / 2 + 0.1f), Color.red, 1000);
RaycastHit h = new RaycastHit ();
return Physics.Raycast (transform.position, -Vector3.up, out h, collider2D.bounds.size.y / 2 + 0.1f);
}
Debug.DrawRay draws a ray into the platform tiles, but Physics.Raycast doesn't seem to detect that there's anything there.
EDIT: So I tried using Raycast2D but it still doesn't detect anything and throws a NullReferenceException.
bool isGrounded(){
Debug.DrawRay (new Vector3(transform.position.x, transform.position.y - collider2D.bounds.size.y / 2 - 0.01f, 0), -Vector3.up * 0.1f, Color.red, 1000);
string name = Physics2D.Raycast (new Vector2(transform.position.x, transform.position.y - collider2D.bounds.size.y / 2 - 0.01f), -Vector2.up, 0.1f, 8).collider.gameObject.name;
return true;//name.Contains ("wood") || name == "wallBottom";
}
Answer by Commoble · Mar 17, 2017 at 03:31 PM
You need to use Physics2D.Raycast to detect 2D colliders.
It still doesn't work.
bool isGrounded(){
Debug.DrawRay (transform.position, -Vector3.up * (collider2D.bounds.size.y / 2 + 0.1f), Color.red, 1000);
string name = Physics2D.Raycast (transform.position, -Vector3.up, collider2D.bounds.size.y / 2 + 0.1f, 8).collider.gameObject.name;
return name.Contains ("wood") || name == "wallBottom";
}
It just says that there is a NullReferenceException. It doesn't hit anything. Before I added the layer$$anonymous$$ask, the ray only hit the player itself.
It's not hitting anything because no objects in your scene exist in that Layer$$anonymous$$ask's layers.
A Layer$$anonymous$$ask isn't the same thing as a layer ID. A layer mask that only includes layer 8 would have a value of 256; likewise, a layer mask with a value of 8 would only include Builtin Layer 3, which is unused and cannot be used. A good way to use layermasks is to declare a public Layer$$anonymous$$ask groundlayers;
field in your script, and set the relevant layers in the Inspector.
Your answer
Follow this Question
Related Questions
RaycastHit.point Collider issue C# 0 Answers
Ray is not being detected 0 Answers
raycastHit.point - How do I make it ignore colliders? 1 Answer