- Home /
Raycasting not working?
So I tried using raycasting to make my enemy AI jump when there is a wall next to him. I am in the first stage of seeing if the raycast works but it isn't working right now. Here is my code:
RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.TransformDirection(Vector2.right));
if (hit && hit.collider.CompareTag("Wall"))
{
Debug.Log("Wall Detected");
}
There is nothing showing in the console. How do I fix this?
Answer by williamfalvo · Jun 29, 2020 at 08:12 AM
Hi, try this type of raycast:
LayerMask wallLayer = LayerMask.GetMask("Wall");
float distance = 5f;
RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.right, distance, wallLayer);
if(hit.collider != null)
{
//do something
}
If you use a raycast with a layerMask, the raycast hit only object with this type of layer.
You can set new layer from inspector, bottom name object and near tag option.
Obviusly, layer name and a distance from origin is also an example in my code to explain the code.
Also to check where your raycast go to hit, try to use a Debug.DrawRay, and adjust the value to your preferences.
Your answer
Follow this Question
Related Questions
Teleport Not Working in Unity 2D 1 Answer
How do i get the Raycast rotation? 1 Answer
My rigidbody2d is passing through the side of a collider2d but it's working on the top 0 Answers
Why this C# Code doesnt works? Raycast problems.. 1 Answer
Why is my Prefab Instantiating when the Scene is Loaded? 2 Answers