So, I’m trying to get my Enemy AI to target the closest NPC to it and move to and attack it. I have tried many different things to get this to work but I cannot seem to be able to figure it out.
using UnityEngine;
using System.Collections;
public class EnemyAI : MonoBehaviour {
private Animator animator;
void Start()
{
animator = this.GetComponent<Animator>();
}
Transform Target;
int lookAtDistance = 3;
public float attackDistance;
public float moveSpeed;
public float tooClose = .5f;
// Update is called once per frame
void Update () {
GameObject player = GameObject.Find ("Player");
Transform playerTransform = player.transform;
Vector2 position = playerTransform.position;
Vector2 enemyPosition = (gameObject.transform.position);
Vector2.Distance (position, enemyPosition);
if (Vector2.Distance (position, enemyPosition) > tooClose) {
if (Vector2.Distance (position, enemyPosition) < lookAtDistance) {
move ();
} else
animator.SetInteger ("Direction", 4);
}
else
animator.SetInteger ("Direction", 4);
if (Vector2.Distance (position, enemyPosition) < attackDistance) {
attack();
}
}
void move()
{
GameObject player = GameObject.Find ("Player");
Transform playerTransform = player.transform;
Vector2 position = playerTransform.position;
Vector2 enemyPosition = (gameObject.transform.position);
if (position.y > enemyPosition.y) {
transform.Translate (Vector2.up * moveSpeed);
animator.SetInteger ("Direction", 2);
}
if (position.y < enemyPosition.y) {
transform.Translate (Vector2.up * -moveSpeed);
animator.SetInteger ("Direction", 0);
}
if (position.x < enemyPosition.x) {
transform.Translate (Vector2.right * -moveSpeed);
animator.SetInteger ("Direction", 1);
}
if (position.x > enemyPosition.x) {
transform.Translate (Vector2.right * moveSpeed);
animator.SetInteger ("Direction", 3);
}
}
void attack(){
}
}
This is my code so far. Any help would be great. What I’m needing is a script that will tell the AI to target something with a certain TAG that is closest to the AI itself.
Thanks for your time!
Hope to hear back soon!