- Home /
A Problem with my AI
Hello, I am trying to write a script in which the AI will follow the player and then when it reaches a certain distance stop. This stop will enable me to later add in an attack animation. However, I also want the enemy to CONTINUE to follow the player when it moves away, once again until it reaches that certain distance with which to stop and Attack. I currently have it so that the enemy follows the player and stops when it reaches too close. However, I don't have the second part, when the enemy continues to follow. Its a relativly short script:
using UnityEngine;
using System.Collections;
public class EnemyAI : MonoBehaviour {
public GameObject target;
public bool foundPlayer;
public Vector3 myPosition;
public float speed = 1.0f;
public EnemyAI myAI;
void Start () {
// Locate the Player object.
if(GameObject.FindWithTag("Player"))
{
myAI = GetComponent<EnemyAI>();
foundPlayer = true;
}
}
void Attack()
{
myPosition = transform.position;
transform.position = Vector3.Slerp(myPosition, target.transform.position, speed * Time.deltaTime);
}
void Update () {
if(foundPlayer == true)
{
if(Vector3.Distance(myPosition, target.transform.position)<2.0f)
{
myAI.enabled = false;
} else
{
Attack();
}
}
}
}
Any help you can give me would be awesome, thanks!
Have a look at this : http://unitygems.com/basic-ai-character/ it has exactly what you need, following, stop and attack and even filed of view and not seeing through walls.
Answer by Radivarig · Apr 14, 2014 at 06:57 PM
From what I see, your attack function is actually move function.
I would use something like this
public float minDistance = 2f, maxDistance = 10f;
void MoveToTarget()
{
myPosition = transform.position;
transform.position = Vector3.Slerp(myPosition,target.transform.position, speed * Time.deltaTime);
}
void Attack(){
//set attack here
}
void Idle(){
//set idle here
}
void Update()
{
float distToTarget = Vector3.Distance(this.position, target.position);
if(distToTarget > minDistance)
{
if(distToTarget > maxDistance)
Idle();
else MoveToTarget();
}
else Attack();
}
Now your AI will start moving to player when he gets in range and when he reaches he will attack, if the player moves away the AI will follow and repeat attack when near player again.
You can additionally add a timer for following, so the AI don't chase forever if attack is not called, or check if distance from a certain point from which AI is allowed to go exceeds your value then stop following and return back.
Well I would not use transform to move a character as it will imply ignore any obstacles. Your logic is right though.
I have taken this example because it is the simplest, and he already used it in his code, and if we wanted to be precise on the subject of moving AI then we would have to use navigation mesh which is a discussion on its own.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Is this making my AI move? 0 Answers