In Unity, I have created an enemy AI and applied a script for it to move and chase the player. But when moving, the enemy hovers in the air. My character also does not have a rigid body, he just has character controller and my enemy AI is child object and an empty object as parent object. I added this to do animation. This is my enemy AI script created in C#:
using UnityEngine;
using System.Collections;
public class AdvancedAi : MonoBehaviour
{
float distance;
public float lookAtDistance, chaseRange, attackRange, moveSpeed, damping, gravity, attackRepeatTime;
public Transform target;
public CharacterController controller;
private Vector3 moveDirection = Vector3.zero;
private float attackTime;
//TODO: add in a function to find controller and to locate and assign the player as the target
void Start()
{
attackTime = Time.time;
}
void Update()
{
distance = Vector3.Distance(target.position, transform.position);
if(distance < lookAtDistance)
{
LookAt();
}
if(distance > lookAtDistance)
{
GetComponent<Renderer>().material.color = Color.green;
}
if (distance < attackRange)
{
AttackPlayer();
}
else if (distance < chaseRange)
{
ChasePlayer();
}
}
void LookAt()
{
GetComponent<Renderer>().material.color = Color.yellow;
Quaternion rotation = Quaternion.LookRotation(target.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
}
void ChasePlayer()
{
GetComponent<Renderer>().material.color = Color.red;
moveDirection = transform.forward;
moveDirection *= moveSpeed;
moveDirection.y -= gravity * Time.deltaTime; // doesn't seem to work right :(
controller.Move(moveDirection * Time.deltaTime);
}
void AttackPlayer()
{
//TODO: Need Attack Animations
if (Time.time > attackTime)
{
Debug.Log("Attack");
attackTime = Time.time + attackRepeatTime;
}
}
void ApplyDamage()
{
chaseRange += 30;
moveSpeed += 2;
lookAtDistance += 40;
}
}