i´m trying to make my player face different enemies based on witch enemy is the closest.
i´m trying to face the closest enemy using transform.lookAt and Vector3.Distance, i´m able to make the it work, but only on the first enemy my player runs in to.
i have made a list of enemy GameObjets, and i´m looping trough them to find the closest enemy and their position.
i´m new to Unity, and game development in general, so please bear with me :)
this is what i got so far.
Vars:
public List targets;
private GameObject[] enemyList;
Roatation:
void rotateToEnemy() {
//check if spawnEnemyes is close
foreach (GameObject target in targets) {
//transform.LookAt (target.transform.position);
if (target != null) {
float enemyDistance = Vector3.Distance (target.transform.position, transform.position);
if (enemyDistance <= 5.0f) {
transform.LookAt (target.transform.position);
Debug.Log (enemyDistance);
}
}
}
}
Add Enemis to list:
void addEnemiesToList() {
//Make enemy list
GameObject[] enemyList = GameObject.FindGameObjectsWithTag("skeletonEnemy");
// Add enem,is to array
foreach(GameObject enemy in enemyList) {
targets.Add (enemy);
}
}
↧