Hi i have read through this question
and i still dont fully understand how to make the ai only travel to you when it sees you
here is my current code its a modifed version of bordr’s ufps simple ai
using UnityEngine;
using System.Collections;
public class AI : MonoBehaviour {
// By BorDr
// 9/7/13
//---------------------------------------------------------------------------------------------
// Use this however you like. Just keep this notice attatched. It is very basic and meant
// for use with the UFPS system. Take your model, add in the animations using the variables,
// add a Nav Mesh Agent for navigation (It is free with Unity 4.2!) a collider for a hitbox,
// an Audio Source with your attack sound to play when your enemy is attacking, and set the Stopping
// Distance on the Navmesh to something less than the Range varible, so the enemy will stop and attack
// when it gets close. Make sure your Player is tagged "Player" or else the enemy will not see the player.
// This is not meant as a complete solution, just something for prototyping. Use UFPS damage handler for AI health.
//---------------------------------------------------------------------------------------------
private Transform PlayerT;
private GameObject Player;
private float Timer = 1.5f;
public int Range;
public float MaxTimer = 1.5f;
public int followRange;
public AudioClip HitNoise;
Animator animator;
// Use this for initialization
void Start () {
//Search for the player, then set the player's transform for navigation.
Player = GameObject.Find("Player[Saveable]");
PlayerT = Player.transform;
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
//The timer system I use is simple. It counts up- when it is at maximum, the enemy can attack.
//When it is not, it recharges in seconds.
if (Timer <= MaxTimer){
Timer += Time.deltaTime;
}
//This is the navigation. The enemy will move toward the player while playing it's running
//animation. If it is in range, it will stop playing the animation.
var distance = Vector3.Distance(transform.position, PlayerT.transform.position);
if (distance < followRange)
{
GetComponent<NavMeshAgent>().destination = PlayerT.position;
animator.SetBool("walk", true);
}
else
{
animator.SetBool("walk", false);
GetComponent<NavMeshAgent>().destination = transform.position;
}
//When the player is in range, the enemy will attack.
if (distance < Range)
{
animator.SetBool("attack",true);
Attack ();
}
else
{
animator.SetBool("attack",false);
}
}
void Attack () {
//If the player is in range, the attack animation will play, the timer will reset, and
//damage will be dealt. The audio clip will be played to add an effect to the attack.
if (Timer >= MaxTimer){
Timer = 0;
PlayerT.GetComponent<vp_PlayerDamageHandler>().Damage(1.0f);
audio.PlayOneShot(HitNoise);
}
//animator.SetBool("attack", false);
}
}