I know this is probally simple, but how can I make the enemy AI stop x amount of distance in front of the player when attacking?
using UnityEngine;
using System.Collections;
public class ZombieAI : MonoBehaviour
{
HealthBarGUI healthbargui;
public Transform player;
public float moveSpeed;
private float damping = 6;
//1 = 0 degrees
//0 = 90 degrees
//-1 = 180 degrees
private float angle = 0;
public float fov; //field of vision
public float attackTime;
public float coolDown;
public float attackDistance = 10;
void Start()
{
attackTime = 0;
coolDown = 1.0f;
}
void Update ()
{
Vector3 direction = player.position - transform.position;
//wander state
if (direction.sqrMagnitude > fov
Vector3.Dot(direction.normalized, transform.forward) < angle)
{
Idle();
}
//attack state
if(direction.sqrMagnitude < fov
Vector3.Dot(direction.normalized, transform.forward) > angle)
{
Attack();
}
if(attackTime > 0)
attackTime -= Time.deltaTime;
if(attackTime < 0)
attackTime = 0;
if(attackTime == 0)
{
ApplyDamage();
attackTime = coolDown;
}
}
void Idle()
{
renderer.material.color = Color.green;
}
void Alerted()
{
renderer.material.color = Color.yellow;
}
void Attack()
{
Quaternion rotation = Quaternion.LookRotation(player.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);
renderer.material.color = Color.red;
}
void ApplyDamage()
{
float distance = Vector3.Distance(player.transform.position, transform.position);
Vector3 dir = (player.transform.position - transform.position).normalized;
float direction = Vector3.Dot(dir, transform.forward);
if(distance < 2.5f)
{
if(direction > 0)
{
HealthBarGUI healthbar = (HealthBarGUI)player.GetComponent("HealthBarGUI");
healthbar.updateHealth(-10);
}
}
}
}