Search Unity

Getting Enemy to chase closest player

Discussion in 'Animation' started by Shears, Aug 23, 2015.

  1. Shears

    Shears

    Joined:
    Jul 7, 2015
    Posts:
    24
    How Can I make the Enemys chase the closest player?? I have the FREE Photon multiplayer on my game..


    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class AI : MonoBehaviour {
    5.  
    6.     public Transform visionPoint;
    7.  
    8.     private Transform player;
    9.  
    10.     public Transform Player;
    11.    
    12.     public float visionAngle = 30f;
    13.     public float visionDistance = 10f;
    14.     public float moveSpeed = 2f;
    15.     public float chaseDistance = 3f;
    16.    
    17.     private Vector3? lastKnownPlayerPosition;
    18.     // Use this for initialization
    19.     void Start () {
    20.         player = GameObject.FindObjectOfType<Transform> ();
    21.     }
    22.    
    23.     // Update is called once per frame
    24.     void Update () {
    25.         Vector3 lookAt = Player.position;
    26.         lookAt.y = transform.position.y;
    27.         transform.LookAt(lookAt);
    28.     }
    29.    
    30.     void FixedUpdate () {
    31.        
    32.     }
    33.    
    34.     void Look () {
    35.         Vector3 deltaToPlayer = player.transform.position - visionPoint.position;
    36.         Vector3 directionToPlayer = deltaToPlayer.normalized;
    37.        
    38.         float dot = Vector3.Dot (transform.forward, directionToPlayer);
    39.        
    40.         if (dot < 0) {
    41.             return;
    42.         }
    43.        
    44.         float distanceToPlayer = directionToPlayer.magnitude;
    45.        
    46.         if (distanceToPlayer > visionDistance)
    47.         {
    48.             return;
    49.         }
    50.        
    51.         float angle = Vector3.Angle (transform.forward, directionToPlayer);
    52.        
    53.         if(angle > visionAngle)
    54.         {
    55.             return;
    56.         }
    57.        
    58.         RaycastHit hit;
    59.         if(Physics.Raycast(transform.position, directionToPlayer, out hit, visionDistance))
    60.         {
    61.             if (hit.collider.gameObject == player.gameObject)
    62.             {
    63.                 lastKnownPlayerPosition = player.transform.position;
    64.             }
    65.         }
    66.     }
    67. }