Hi guys, the question is how to make the enemy continue search its target after its initial target has been killed?
(UPDATED: i have successfully make the AI able to kill its target and go back to its waypoint but now the problem is it doesn’t bother about the other target which carry the same tag, how do i make it hit other target as well?)
var targetObject : GameObject;
function DetectEnemy()
{
if (targetObject == null && GameObject.FindWithTag("Player1"))
targetObject = GameObject.FindWithTag("Player1");
}
function Start () {
// Auto setup player as target through tags
Patrol();
}
function Patrol () {
var curWayPoint = AutoWayPoint1.FindClosest(transform.position);
while (true) {
var waypointPosition = curWayPoint.transform.position;
// Are we close to a waypoint? -> pick the next one!
if (Vector3.Distance(waypointPosition, transform.position) < pickNextWaypointDistance)
curWayPoint = PickNextWaypoint (curWayPoint);
// Attack the player and wait until
// - player is killed
// - player is out of sight
if (CanSeeTarget ())
yield StartCoroutine("AttackPlayer");
// Move towards our target
MoveTowards(waypointPosition);
yield;
}
}
function CanSeeTarget () : boolean {
DetectEnemy();
if (Vector3.Distance(transform.position, targetObject.transform.position) > attackRange)
return false;
var hit : RaycastHit;
if (Physics.Linecast (transform.position, targetObject.transform.position, hit))
return hit.transform == targetObject.transform;
return false;
}
function AttackPlayer () {
var lastVisiblePlayerPosition = targetObject.transform.position;
while (true) {
if (CanSeeTarget ()) {
// Target is dead - stop hunting
if (targetObject.transform == null)
return;
// Target is too far away - give up
var distance = Vector3.Distance(transform.position, targetObject.transform.position);
if (distance > shootRange * 3)
return;
lastVisiblePlayerPosition = targetObject.transform.position;
if (distance > dontComeCloserRange)
MoveTowards (lastVisiblePlayerPosition);
else
RotateTowards(lastVisiblePlayerPosition);
var forward = transform.TransformDirection(Vector3.forward);
var targetDirection = lastVisiblePlayerPosition - transform.position;
targetDirection.y = 0;
var angle = Vector3.Angle(targetDirection, forward);
// Start shooting if close and play is in sight
if (distance < shootRange && angle < shootAngle)
yield StartCoroutine("Shoot");
} else {
yield StartCoroutine("SearchPlayer", lastVisiblePlayerPosition);
Debug.Log("Test inside Attack 1");
// Player not visible anymore - stop attacking
if (!CanSeeTarget ())
return;
}
yield;
}
}
function SearchPlayer (position : Vector3) {
// Run towards the player but after 3 seconds timeout and go back to Patroling
var timeout = 3.0;
while (timeout > 0.0) {
MoveTowards(position);
// We found the player
if (CanSeeTarget ())
return;
timeout -= Time.deltaTime;
yield;
}
}