Hi guys i create a script for Enemy AI but i hv an issue now… the enemy is chasing and everything but when is in range to attack my hp decrease in every frame non stop, instead of decrease in each attack… Can anyone help me plz? there is my 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;
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)
{
Attack ();
}
}
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);
}
}
}
Update() is called every frame, and because you call the Attach() method inside Update() it will also be called every frame (as long as distance <= range).
There are several ways of solving this, but in this case it can be dealt with in a simple manner because we’re talking about an enemy AI (which doesn’t care about the feel of the game).
Personally, I would have used a timer for this, so that a clock ticks down between each attack. Something like this (untested):
Ideally, you would probably want to put all the timer logic inside the Attack() method, and have that return the amount of damage applied or something.