Hey guys, im just wondering how i can get my AI to constantly go for the closest target to it?
Like if my friend and i are playing and im next to the AI, it will chase me, then i run past my friend and the AI is closest to my friend it will chase him?
Here is my current script:
var target : Transform; //the enemy's target
var moveSpeed = 3; //move speed
var rotationSpeed = 3; //speed of turning
var myTransform : Transform; //current transform data of this enemy
var gravity = 20;
var closest : GameObject;
function Awake()
{
myTransform = transform; //cache transform data for easy access/preformance
}
function Start()
{
// target = GameObject.FindWithTag("Player").transform; //target the player
}
function Update ()
{
var targets : GameObject[] = GameObject.FindGameObjectsWithTag("Player");
var targetNumber : int = Random.Range(0,targets.length - 1);
target = targets[targetNumber].transform;
//rotate to look at the player
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
//move towards the player
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
You need to loop through each gameObject and check the distance, saving the closest. Take a look at this code from the Unity docs.
// Print the name of the closest player
print(FindClosestEnemy().name);
// Find the name of the closest player
function FindClosestEnemy () : GameObject {
// Find all game objects with tag Player
var gos : GameObject[];
gos = GameObject.FindGameObjectsWithTag("Player");
var closest : GameObject;
var distance = Mathf.Infinity;
var position = transform.position;
// Iterate through them and find the closest one
for (var go : GameObject in gos) {
var diff = (go.transform.position - position);
var curDistance = diff.sqrMagnitude;
if (curDistance < distance) {
closest = go;
distance = curDistance;
}
}
return closest;
}
Yeah, i found this code yesterday and i cant figure out how to add it to my code, my game is a multiplayer fps, and i have AI for testing some things and when i aim at the terrain and press Q it spawns the AI, and i want it to continuously try to find the closest Player to it and follow that player untill a player gets closer to it than that player. But i cant figure out how to put it in the code.
Thats what i need help with, been trying and still cant do it.