I've got this NPC walking around and I'm trying to create a cone to represent their line of sight, including how it would be blocked by buildings, similar to how Nicky Case has implemented it as described here: https://ncase.me/sight-and-light/

My main problem with this, right now, is that it seems like I'm not detecting collisions between my 2D box colliders and Physics2D.Raycast when I would expect to much of the time. The green rays in the image below are NOT colliding (this is fine on the corners, I don't really care, but when the rays are going straight through walls, that's a big problem for me). Red rays are colliding.

Why aren't the Physics2D.Raycasts reliably colliding with the 2D Box Collider walls?

I believe everything is in the same z-plane and has the correct collision matrix in place.

![ ]image of my NPC and raycasts from them at various points along their path

    List<UnityEngine.Vector2> endPoints = new List<UnityEngine.Vector2>();
    GameObject[] corners = GameObject.FindGameObjectsWithTag("verticies");

    for(int i = 0; i < corners.Length; i++) {
        UnityEngine.Vector2 corner = new UnityEngine.Vector2(corners[i].transform.position.x, corners[i].transform.position.y);
        RaycastHit2D endPoint = Physics2D.Raycast(this.transform.position, corner);
        if(endPoint.collider != null) {
            Debug.DrawLine (this.transform.position, endPoint.point, Color.red);
        } else {
            Debug.DrawLine (this.transform.position, corner, Color.green);

1 Answer 1


The problem is in line:

RaycastHit2D endPoint = Physics2D.Raycast(this.transform.position, corner);

In the docs it mentions that the second parameter of Physics2D.Raycast is the direction of the ray and not the target position.

So what you have to do is to subtract target position (corner) from player position and normalize the vector in order to get the direction of the ray.

  • \$\begingroup\$ You can also use LineCast if you prefer to express your query with an end position. \$\endgroup\$
    – DMGregory
    Commented Feb 10, 2020 at 8:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .