V
V
Vqrlamov2022-01-06 13:53:41
Unity
Vqrlamov, 2022-01-06 13:53:41

How to determine the Transform of many enemies?

Help needed, the script turns the player to face the enemy if the player is in range of an enemy, but this only works with the Transform of a specific enemy. How to make it possible to perform this action with Transform of many enemies?

using UnityEngine;

public class LookAtEnemyLogic : MonoBehaviour
{
    private bool onEnemyZone;

    public Transform enemy;
    public float speed;

    void Update()
    {
        if (onEnemyZone)
        {   
            // Плавный поворот на врага
            var targetRotation = Quaternion.LookRotation(enemy.transform.position - transform.position);
            transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, speed * Time.deltaTime);
        }
    }

    private void OnTriggerStay(Collider player)
    {
        if (player.gameObject.CompareTag("Enemy"))
        {
            onEnemyZone = true;
        }
        else
        {
            onEnemyZone = false;
        }
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
Farawa, 2022-01-06
@Vqrlamov

As an option to store the transforms of all enemies, in the update at the beginning add a check for the presence of an enemy, if there is no enemy, then run through the array and compare the distance between the player and the enemy, take the closest one that is within the radius of destruction and add it as a target

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question