Hi guys i hv a enemy ai script. everything works fine but now when i put the animation my enemy chase me and when he start hit i take the damage but it dont play attack animation. it just keep running near my wild do the damage. I know thats probably a problem of prioratize the atack animation over the run animation but i try lots of changes and im not getting ther can anyone help plz?
This is the script:
using UnityEngine;
using System.Collections;
public class EnemyAI : MonoBehaviour
{
float distance;
float lookAtDistance = 25.0f;
float chaseRange = 15.0f;
float damping = 6.0f;
float range = 1.25f;
float attackDelay = 1.0f;
float nextAttackTime = 0.0f;
public int damage;
public int speed;
bool isReturning;
public AnimationClip idle;
public AnimationClip run;
public AnimationClip attack;
public Transform target;
private Vector3 initialPosition;
public CharacterController controller;
void Start()
{
initialPosition = transform.position;
isReturning = false;
}
void Update()
{
if (!isReturning)
{
distance = Vector3.Distance(target.position, transform.position);
if (distance < lookAtDistance)
{
animation.CrossFade (idle.name);
LookAt (target.position);
}
if(distance > lookAtDistance && distance > chaseRange) //LookDistance is always bigger than the attackRange so i commented it out. //if (distance > lookAtDistance) && distance>attackRange)
{
isReturning = true;
animation.CrossFade(run.name);
}
if (distance < chaseRange)
{
transform.LookAt(target.position);
controller.SimpleMove(transform.forward*speed);
animation.CrossFade(run.name);
}
if(distance <= range)
{
if(Time.time > nextAttackTime)
{
nextAttackTime = Time.time + attackDelay;
Attack ();
}
}
else
{
nextAttackTime = Time.time + attackDelay;
}
}
else
{
LookAt (initialPosition);
MovePlayerForward();
distance = Vector3.Distance(initialPosition, transform.position);
if (distance <20)
{
isReturning = false;
}
}
}
void LookAt(Vector3 targetPosition)
{
Quaternion rotation = Quaternion.LookRotation(targetPosition - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
}
void MovePlayerForward()
{
transform.Translate(Vector3.forward * speed * Time.deltaTime);
}
private void Attack()
{
float distance = Vector3.Distance (target.transform.position, transform.position);
if (distance < 1.5f)
{
animation.Play(attack.name);
PlayerHealth ph = (PlayerHealth)target.GetComponent("PlayerHealth");
ph.AdjustCurrentHealth(damage);
}
}
}