Hi! I am starting to write AI code and I’m having some issues with a very simple AI.
The issue:
I want the enemy to stop as soon as he enters the maxDistance variable, so he cannot keep going forward. I think my code is right, but it doesn’t work and I can’t find the
problem. Thank you!
The code:
using UnityEngine;
using System.Collections;
public class BasicAI : MonoBehaviour {
private GameObject player;
public float distance;
private CharacterController thischar;
public float speed = 5.0f;
public Vector3 movementh = Vector3.zero;
public float chaseRange = 1.0f;
public float attackRange = 1.5f;
public float gravity = 20.0f;
public float lookatdistance = 20.0f;
public float dumping = 8.0f;
public float maxDistance = 0.4f;
// Use this for initialization
void Start () {
player = GameObject.FindWithTag ("Player");
thischar = GetComponent <CharacterController>();
}
// Update is called once per frame
void Update () {
distance = Vector3.Distance (player.transform.position, transform.position);
movementh.y -= gravity * Time.deltaTime;
thischar.Move (movementh * Time.deltaTime);
if (distance <= chaseRange)
{
if (distance >= maxDistance)
{
movementh = transform.forward * speed;
print ("la distancia es mas grande que la maxima");
}
else
{
movementh = Vector3.zero;
}
}
else
{
if (distance <= lookatdistance)
{
LookAt ();
}
}
}
void LookAt ()
{
Quaternion rotation = Quaternion.LookRotation (player.transform.position - transform.position);
transform.rotation = Quaternion.Slerp (transform.rotation, rotation, Time.deltaTime * dumping);
}
}