Curtis Jones
Curtis Jones

Reputation: 39

Raycast2D not colliding with wall

I have this code

        RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.right, Mathf.Infinity, LayerMask.NameToLayer("Wall"));
        Debug.DrawRay(transform.position, Vector2.right);

        if(hit.collider != null)
        {
            Debug.Log("Wall");
        }

and this is the wall I want it to collide with
https://i.sstatic.net/KGQcS.png
But when I run the debug ray goes right over the wall but I don't get any message back

Upvotes: 1

Views: 256

Answers (1)

BugFinder
BugFinder

Reputation: 17858

raycasts use a mask, the way that works your code RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.right, Mathf.Infinity, LayerMask.NameToLayer("Wall"));

needs a subtle change

try RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.right, Mathf.Infinity, ~1<<LayerMask.NameToLayer("Wall"));

the 1<< shifts the bits. the ~ makes the compliment

This is covered in the raycast docs on unity (while its listed under the 3d, it still applies https://docs.unity3d.com/ScriptReference/Physics.Raycast.html)

Upvotes: 2

Related Questions