- Home /
Modification of AIFollow.cs Pathfinding
I modified the code AIFollow.cs and i add the functions code. And this functions are GetEnemies() and FindClosest() . I want to try Real Time Strategy game and i also use it for A* pathfinding. There are not working. GetEnemies() create an array which includes "Target" tag of GameObjects. But it is not working.
Any help i will appriciate.
Here is the Code:
using UnityEngine;
using System.Collections;
public class AIFollow : MonoBehaviour { //[RequireComponent (typeof(CharacterController))] public float speed = 3.0F; public float rotationSpeed = 5.0F; public float pickNextWaypointDistance = 3.0F; public float SearchWaypointFrequency = 0.2F; public float maxStop = 3;
public bool continousTargetSearch = false; public float targetSearchFrequency = 1.0F; private bool canSearchAgain = true; public Command command = Command.Stay;
public Transform target; private CharacterController controller; private AIAnimation animator; private Seeker seeker;
public Vector3 myPosition; public Transform[] enemies; public float distance;
// Make sure there is always a character controller
public enum Command { Stay, Walk }
public IEnumerator Start () { //public IEnumerator Start ()
waypointPosition = transform.position;
command = Command.Stay;
controller = GetComponent (typeof(CharacterController)) as CharacterController;
Object anim = GetComponent (typeof(AIAnimation));
animator = anim != null ? anim as AIAnimation : null;
seeker = GetComponent (typeof(Seeker)) as Seeker;
StartCoroutine (Patrol());
yield return new WaitForSeconds (Random.value*0.5F);
if (continousTargetSearch) {
StartCoroutine (SearchPlayer());
}
//here is the start array operations
GetEnemies();
myPosition = transform.position;
target = FindClosest(enemies);
distance=Vector3.Distance(target.position,transform.position);
while (true) {
FindPoint (curpoint);
yield return new WaitForSeconds (SearchWaypointFrequency);
}
}
private Vector3 waypointPosition; //private bool continuous = false; private Vector3[] points; private int curpoint = 0;
public void Update () { //Debug.color = Color.blue; Debug.DrawLine (transform.position, waypointPosition, Color.blue);
//Stop();
Start();
/*GetEnemies();
myPosition = transform.position;
target = FindClosest(enemies);
distance=Vector3.Distance(target.position,transform.position);*/
}
public IEnumerator SearchPlayer () { yield return 0; while (true) { yield return 0; while (!canSearchAgain) { yield return 0; } if (continousTargetSearch) { canSearchAgain = false; seeker.StartPath (transform.position,target.position); } yield return new WaitForSeconds (targetSearchFrequency); }
}
public void PathComplete (Vector3[] newPoints) { canSearchAgain = true; points = newPoints; FindPoint (0); command = Command.Walk; }
public void PathError () { canSearchAgain = true; }
public bool HasReachedTarget () { return curpoint >= points.Length; }
public void FindPoint (int cpoint) { curpoint = cpoint; if (points == null || points.Length == 0 || curpoint >= points.Length) {
waypointPosition = transform.position; Stop (); return; }
if (points.Length == 1) {
waypointPosition = points[0];
command = Command.Walk;
return;
}
command = Command.Walk;
waypointPosition = points[curpoint];
Vector3 p = waypointPosition;
p.y = transform.position.y;
if (curpoint < points.Length - 1) {
if ((transform.position-p).sqrMagnitude < pickNextWaypointDistance*pickNextWaypointDistance) {
curpoint++;
FindPoint (curpoint);
}
} else {
if ((transform.position-p).sqrMagnitude < maxStop*maxStop) {
curpoint++;
FindPoint (curpoint);
}
}
}
public IEnumerator Patrol () { while (true) { if (command == Command.Walk) { MoveTowards(waypointPosition); }
yield return 0;
}
}
public void Stop () { command = Command.Stay; if (animator != null) { animator.SetSpeed (0.0F); } }
public void RotateTowards (Vector3 position) { if (animator != null) { animator.SetSpeed (0.0F); }
Vector3 direction = position - transform.position;
direction.y = 0;
if (curpoint == points.Length - 1 && direction.sqrMagnitude < maxStop*maxStop) {
FindPoint (curpoint);
return;
}
if (direction.sqrMagnitude < 0.1F*0.1F) {
return;
}
// Rotate towards the target
transform.rotation = Quaternion.Slerp (transform.rotation, Quaternion.LookRotation(direction), rotationSpeed * Time.deltaTime);
transform.eulerAngles = new Vector3(0, transform.eulerAngles.y, 0);
}
public void MoveTowards (Vector3 position) { Vector3 direction = position - transform.position; direction.y = 0;
if (direction.sqrMagnitude < 0.2F*0.2F) {
Stop ();
return;
}
// Rotate towards the target
transform.rotation = Quaternion.Slerp (transform.rotation, Quaternion.LookRotation(direction), rotationSpeed * Time.deltaTime);
transform.eulerAngles = new Vector3(0, transform.eulerAngles.y, 0);
// Modify speed so we slow down when we are not facing the target
Vector3 forward = transform.TransformDirection(Vector3.forward);
float speedModifier = Vector3.Dot(forward, direction.normalized);
speedModifier = Mathf.Clamp01(speedModifier);
// Move the character
if (controller) {
direction = forward * speed * speedModifier*speedModifier;
controller.SimpleMove(direction);
} else {
direction = forward * speed * speedModifier*speedModifier;
transform.Translate (direction*Time.deltaTime,Space.World);
}
if (animator != null) {
animator.SetSpeed (speed * speedModifier);
}
}
public void GetEnemies(){ // Get enemies from the Scene
GameObject[] enemyObjects = GameObject.FindGameObjectsWithTag("Target");
Transform[] enemies = new Transform[enemyObjects.Length];
for (int i = 0; i < enemyObjects.Length; i++)
{
enemies[i] = enemyObjects[i].transform;
Debug.Log("GetEnemies() : count = " + i );
}
Debug.Log("GetEnemies() : enemy count = " + enemies.Length);
}
public Transform FindClosest(Transform[] targets) // Find Closest enemy { Debug.Log("FindClosest() : ---------------> " +targets.Length);
GameObject[] enemyObjects = GameObject.FindGameObjectsWithTag("Target");
float closestDistance = (enemies[0].position-myPosition).sqrMagnitude;
int targetNumber=0;
for(int i=1; i<targets.Length ;i++)
{
float thisDisatance = (enemies[i].position-myPosition).sqrMagnitude;
if(thisDisatance<closestDistance)
{
closestDistance=thisDisatance;
targetNumber=i;
}
}
return enemies[targetNumber];
}
}
enemy must detect the target from an array and goes through it. Then Fire() and Destroy "target". After getting another target from an array and goes to the next target.
Your answer
![](https://koobas.hobune.stream/wayback/20220613092322im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
walking through the countryside ? 1 Answer
2D alternative to Physics.CheckSphere 2 Answers
Patfinding cant change destination Target 0 Answers
Connecting the dots 0 Answers
Navmesh with destructible obstacles 1 Answer