- Home /
Help with AI follow range
Hi i have this cs script that controls my mob in my game, and the mob instantly begins to chase my player when i start the game, but i would like it so that it wont start chasing the player unless it is within a specific range. I am a little unsure of how i could do this. I have tried several ways but always ended up more confused than before.
The following is my mob script
using UnityEngine;
using System.Collections;
public class Mob : MonoBehaviour
{
public float speed;
public float range;
public CharacterController controller;
public Transform player;
private Fighter opponent;
public AnimationClip run;
public AnimationClip idle;
public AnimationClip die;
public AnimationClip attackClip;
public double impactTime = 0.35;
public int health;
public int damage;
private bool impacted;
public int movementrange;
// Use this for initialization
void Start ()
{
opponent = player.GetComponent<Fighter> ();
}
// Update is called once per frame
void Update ()
{
if(!isDead())
{
if(!inRange ())
{
chase ();
}
else
{
animation.Play(attackClip.name);
attack();
if(animation[attackClip.name].time>0.9*animation[attackClip.name].length)
{
impacted = false;
}
}
}
else
{
dieMethod();
}
}
void attack()
{
if(animation[attackClip.name].time>animation[attackClip.name].length * impactTime&&!impacted&&animation[attackClip.name].time<0.9*animation[attackClip.name].length)
{
opponent.getHit(damage);
impacted = true;
}
}
bool inRange()
{
if(Vector3.Distance(transform.position, player.position)<range)
{
return true;
}
else
{
return false;
}
}
public void getHit(int damage)
{
health = health - damage;
if(health<0)
{
health = 0;
}
}
void chase()
{
transform.LookAt(player.position);
controller.SimpleMove (transform.forward*speed);
animation.CrossFade(run.name);
}
void dieMethod()
{
animation.Play (die.name);
if(animation[die.name].time>animation[die.name].length*0.9)
{
Destroy(gameObject);
}
}
bool isDead()
{
if(health <= 0)
{
return true;
}
else
{
return false;
}
}
void OnMouseOver()
{
player.GetComponent<Fighter>().opponent = gameObject;
}
}
Thanks in advance!
Comment