2D Top-Down Field of View Cone

Hello,

I am using a raycast 2D from my player to try to detect enemies within a certain range. At the moment it is sending a single line out, but this means the player has to be very precise (and obviously they cannot see the DrawRay line in game mode).

What I want to do is implement a simple Field of View (FOV) cone so that I can detect enemies within an area, but I am really struggling to find a tutorial that covers this. I have been searching, but I mostly find implementations for 3D and those that do cover 2D are based on making the FOV follow the mouse cursor. I am building my game for mobile and using a joystick controller on screen, so need it to be based on the direction the player is facing, not a cursor.

Does anyone know of a tutorial that covers 2D top-down FOV like this?

The code I have so far for my raycast in the Update function is:

public void Update() {
        movement.x = joystick.Horizontal;
        movement.y = joystick.Vertical;
        Vector2 dir = movement;
        dir.Normalize();
  
        if (movement == Vector2.zero) {
            dir = new Vector2(lastX, lastY);
            dir.Normalize();
        }

        Vector2 start = transform.position;

        Debug.DrawRay(start, dir * _raycastHitDistance, Color.green);

        RaycastHit2D hit = Physics2D.Raycast(start, dir, _raycastHitDistance, 1 << LayerMask.NameToLayer("Enemy"));
        if (hit.collider != null) {
            if (hit.collider.gameObject != gameObject) {
                Debug.Log("Collider is: " + hit.collider);
            }
        }
    }

Many Thanks,

J

The easiest thing is to find everything withing a circle (Physics2D.OverlapCircle), and then restrict it to only the things within a certain angle.

Finding the angle between a target and your look direction is just Vector2.Angle(target.position - transform.position, transform.forward)

1 Like

Hi Baste,

Thank you for your reply. I am not sure about the target.position because I am just looking for any collisions where the tag = enemy. Not sure how to do that?

Many Thanks,