Hello,
I am relatively new to coding and am trying to make this AI script work with navmesh so that an object ‘Enemy’ does the following;
-
- looks at the player within a certain distance
-
- Moves towards the player within a certain
-
- once it is doing 2 and reaches 1.5 away from the player it stops
-
- it continuously follows the player until the player gets a certain distance away from it
-
- it moves around objects
I did have 1 to 4 working properly but since ive added the Nav Mesh part to my script the Enemy completes 1 and 2 and 5 but not 3 or 4, it just follows the player continuously. Here is my script for the enemy object, the ‘function chase’ is the part I changed in order for the Nav Mesh thing to work. Note the lines I commented out:
var Distance;
var Target : Transform;
var lookAtDistance = 25.0;
var chaseRange = 15.0;
var attackRange = 1.5;
var moveSpeed = 5.0;
var Damping = 6.0;
var attackRepeatTime = 1;
var TheDamage = 40;
private var attackTime : float;
var controller : CharacterController;
var gravity : float = 20.0;
private var MoveDirection : Vector3 = Vector3.zero;
function Start ()
{
attackTime = Time.time;
}
function Update ()
{
Distance = Vector3.Distance(Target.position, transform.position);
if (Distance < lookAtDistance)
{
lookAt();
}
if (Distance > lookAtDistance)
{
renderer.material.color = Color.green;
}
if (Distance < attackRange)
{
attack();
}
else if (Distance < chaseRange)
{
chase ();
}
}
function lookAt ()
{
renderer.material.color = Color.yellow;
var rotation = Quaternion.LookRotation(Target.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * Damping);
}
function chase ()
{
renderer.material.color = Color.red;
//moveDirection = transform.forward;
//moveDirection *= moveSpeed;
GetComponent(NavMeshAgent).destination = Target.position;
// moveDirection.y -= gravity * Time.deltaTime;
//controller.Move(moveDirection * Time.deltaTime);
}
function attack ()
{
if (Time.time > attackTime)
{
Target.SendMessage("ApplyDamage", TheDamage);
Debug.Log("The Enemy Has Attacked");
attackTime = Time.time + attackRepeatTime;
}
}
function ApplyDamage ()
{
chaseRange += 30;
moveSpeed += 2;
lookAtDistance += 40;
}
If there is any lack of clarity feel free to ask, thanks.