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?
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.