- Home /
Question by
Alphacreations · Jun 30, 2020 at 08:50 AM ·
raycastcollider2draycasting
raycast not hitting anything?
So I am trying to make a 2d platformer and I want my enemy AI to jump when there is a wall in front of it. I am trying to use raycasts but they are not working. I have a box collider 2d for the wall. Here is my code:
RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.right, 10,
LayerMask.NameToLayer("Wall"));
if (hit)
{
Debug.Log("wall detected");
}
yet I am not getting any messages in the console. could somebody help me?
Comment
You have to provide a layer mask not the layer index (which is what NameToLayer
returns)
RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.right, 10,
1 << Layer$$anonymous$$ask.NameToLayer("Wall"));
Answer by FeedMyKids1 · Jun 30, 2020 at 09:38 AM
As is, you are not casting with the "Wall" LayerMask. You have to do a bit shift in order to make it a layermask.
So right now, LayerMask.NameToLayer ("Wall") just returns the int layer that Wall is on.
You should do the following instead:
RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.right, 10, 1 << LayerMask.NameToLayer("Wall"));
if (hit)
Debug.Log("wall detected");
1<< is the bit shift that turns the "Wall" layer into a layermask.