- Home /
Player doesn't detect ground by using Raycast
Hey, For some reason my Player doesn't detect the ground properly, I can't find the issue or why is it happening but it has to be something with the layer,And I already checked. There's a layer called Ground. Here is my code:
// If the Player is Grounded
bool Is_Grounded = Physics2D.Raycast(transform.position, transform.position - (new Vector3(0, 0.6f)), -0.6f, LayerMask.NameToLayer("Ground"));
Debug.DrawLine(transform.position, transform.position - (new Vector3(0, 0.6f)), Color.black, 1f);
if (Is_Grounded == true)
{
Debug.Log("Grounded");
}
if( Is_Grounded == false)
{
Debug.Log("Not Grounded");
}
Thanks for the help
Answer by homer_3 · Sep 27, 2020 at 01:43 PM
Change "LayerMask.NameToLayer("Ground")" to "1 << LayerMask.NameToLayer("Ground")".
Thanks for your advice, unfortunately, I already tried that and it kind of worked... Well, It worked as long as I stayed in the spawn position, As soon as I move in any direction it won't detect the ground any more for some reason
Your 2nd argument to Raycast is also kind of weird, which could be causing you issues. It's actually saying to cast the ray away from that fixed point. I'd use Vector2.down instead.
You're also using a negative distance in your 3rd argument, which doesn't make any sense.
Yeah, The negative distance & the direction was the problem, I have changed the code to this and everything is working fine now.
Is_Grounded = Physics2D.Raycast(transform.position, Vector2.down, 0.6f, 1 << Layer$$anonymous$$ask.NameToLayer("Ground"));
Debug.DrawLine(transform.position, transform.position + Vector3.down, Color.black, 1f);
Thank you very much for your kindness and help @homer_3 , Appreciate it!
Your answer
Follow this Question
Related Questions
Raycast distance affected by momentum of character 0 Answers
Reset raycast when an object exits 1 Answer
Fixed bullet spread 1 Answer
physics.raycast nullReferenceException 1 Answer
Move raycast.point to transform.position 0 Answers