Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Enemy Angle?

Discussion in 'Scripting' started by Cooper37, Aug 31, 2014.

  1. Cooper37

    Cooper37

    Joined:
    Jul 21, 2012
    Posts:
    383
    Hi! I'm trying to test some enemy detection AI, but I have a slight problem. It works for the most part except the enemy cannot detect if the player is in its front line of view. How can I do this:
    Code (csharp):
    1.  
    2. var detectRadius : float = 30.0;
    3. var viewSpread : float = 40.0;
    4. function Update        (){
    5.     //Detect Radius
    6.     if(Vector3.Distance(player.position, transform.position) > detectRadius){
    7.         Debug.Log("The Enemy cannot see you...");
    8.     }
    9.     if(Vector3.Distance(player.position, transform.position) < detectRadius){
    10.         Debug.Log("Be careful! You're close to an enemy!");
    11.         if(//The player is in enemy sights...){
    12.             Debug.Log("You've been spotted! RUN!");
    13.         }
    14.     }
    15. }
    16. function OnDrawGizmosSelected    (){
    17.     //Detect Radius
    18.     Gizmos.color = Color.yellow;
    19.     Gizmos.DrawWireSphere(transform.position,detectRadius);
    20.     //View Radius
    21.     Gizmos.color = Color.magenta;
    22.     Gizmos.DrawRay(transform.position,Quaternion.AngleAxis(viewSpread, transform.up) * transform.forward * detectRadius);
    23.     Gizmos.DrawRay(transform.position,Quaternion.AngleAxis(-viewSpread, transform.up) * transform.forward * detectRadius);
    24. }
    25.  
    This is how the gizmos draw it. How can I detect if the player is between the pink lines:
     
  2. Fraconte

    Fraconte

    Joined:
    Dec 6, 2013
    Posts:
    327
  3. Cooper37

    Cooper37

    Joined:
    Jul 21, 2012
    Posts:
    383
    I guess a little more research could've helped.lol Anyways, it's SOLVED:
    Code (csharp):
    1.  
    2.         if(Vector3.Angle(player.position - transform.position, transform.forward) < viewSpread){
    3.             Debug.Log("You've been spotted! RUN!");
    4.         }
    5.  
    Thanks! :)
     
    Last edited: Sep 1, 2014
    Fraconte likes this.