A
A
Alon Mix2018-02-01 14:58:50
Unity
Alon Mix, 2018-02-01 14:58:50

Autocannon 2d and how to figure it out?

Hello. I was looking for a video on autocannon in 2d and as a result there are practically no video tutorials or they are in 3d. Of course, it didn’t bother me to remake them for my project, but there is one nuance that I still can’t decide.

public class AI : MonoBehaviour {
[Header ("Характеристики")]
public Transform target;

public Transform Tower;
public float speedTurn = 5f;
public float range = 10f;

public string enemyTag = "Enemy";

private void Start()
{

    InvokeRepeating("UpdateTarget", 0f, 0.5f);
}

void Update()
{

    if (target == null)
        return;

    Vector3 direction = target.position - transform.position;
    Quaternion lookRotation = Quaternion.LookRotation(direction);
    Vector3 rotation = Quaternion.Lerp(Tower.rotation, lookRotation, Time.deltaTime * speedTurn).eulerAngles;
    Tower.rotation = Quaternion.Euler(0f, 0f, rotation.z); 



}

void UpdateTarget()
{

        GameObject[] enemies = GameObject.FindGameObjectsWithTag(enemyTag);        
        float shortesDistance = Mathf.Infinity;
        GameObject nearesEnemy = null;
        foreach (GameObject enemy in enemies)
        {
            float distanceToEnemy = Vector3.Distance(transform.position, enemy.transform.position);
            if (distanceToEnemy < shortesDistance)
            {
                shortesDistance = distanceToEnemy;
                nearesEnemy = enemy;
            }
        }

        if (nearesEnemy != null && shortesDistance <= range)
        {
            target = nearesEnemy.transform;
        }
        else
        {
            target = null;
        }
    }

private void OnDrawGizmosSelected()
{
    Gizmos.color = Color.blue;
    Gizmos.DrawWireSphere(transform.position, range);
}


}

The problem itself is that the "gun" finds the "enemy" at close range, namely, it begins to turn towards him.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question