Search Unity

Question 2D Top-Down Field of View Cone

Discussion in 'Scripting' started by johnc81, Aug 4, 2020.

  1. johnc81

    johnc81

    Joined:
    Apr 24, 2019
    Posts:
    142
    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:

    Code (CSharp):
    1. public void Update() {
    2.         movement.x = joystick.Horizontal;
    3.         movement.y = joystick.Vertical;
    4.         Vector2 dir = movement;
    5.         dir.Normalize();
    6.  
    7.         if (movement == Vector2.zero) {
    8.             dir = new Vector2(lastX, lastY);
    9.             dir.Normalize();
    10.         }
    11.  
    12.         Vector2 start = transform.position;
    13.  
    14.         Debug.DrawRay(start, dir * _raycastHitDistance, Color.green);
    15.  
    16.         RaycastHit2D hit = Physics2D.Raycast(start, dir, _raycastHitDistance, 1 << LayerMask.NameToLayer("Enemy"));
    17.         if (hit.collider != null) {
    18.             if (hit.collider.gameObject != gameObject) {
    19.                 Debug.Log("Collider is: " + hit.collider);
    20.             }
    21.         }
    22.     }
    Many Thanks,

    J
     
  2. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,338
    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)
     
    ink13 likes this.
  3. johnc81

    johnc81

    Joined:
    Apr 24, 2019
    Posts:
    142
    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,