我想自动找到敌人并将目标放在最近的敌人身上.统一 3D [英] I want to find automatically enemies and put a target on the closest of them. Unity 3D

查看:33
本文介绍了我想自动找到敌人并将目标放在最近的敌人身上.统一 3D的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将目标放在:最近的位置.

I would like to put a target on the location of : closest.

附言我是新手.

public class ExampleClass : MonoBehaviour
{
    public GameObject FindClosestEnemy()
    {
        GameObject[] gos;
        gos = GameObject.FindGameObjectsWithTag("Enemy");
        GameObject closest = null;
        float distance = Mathf.Infinity;
        Vector3 position = transform.position;
        foreach (GameObject go in gos)
        {
            Vector3 diff = go.transform.position - position;
            float curDistance = diff.sqrMagnitude;
            if (curDistance < distance)
            {
                closest = go;
                distance = curDistance;
            }
        }    //can i put for exemple this specific gameobjet (target)
             //on the closest enemyobject
             //target.transform.position = closest.transform.position;
        return closest;
     }
}

让炮塔跟随我想的目标,但会自动找到最近的目标,我只是还不明白

Making a turret follow a target i figured, but automatically find a closest target i just don't understand yet

推荐答案

您可以简单地使用 Linq OrderBy首先得到最近的物体

You could simply use Linq OrderBy and First to get the closest object

using System.Linq;
...

public GameObject FindClosestEnemy()
{
    GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy");

    // If no enemies found at all directly return nothing
    // This happens if there simply is no object tagged "Enemy" in the scene
    if(enemies.Length == 0)
    {
        Debug.LogWarning("No enemies found!", this);
        return null;
    }

    GameObject closest;

    // If there is only exactly one anyway skip the rest and return it directly
    if(enemies.Length == 1)
    {
        closest = enemies[0];
        target.transform.position = closest.transform.position;
        return closest;
    }


    // Otherwise: Take the enemies
    closest = enemies
    // Order them by distance (ascending) => smallest distance is first element
        .OrderBy(go => (position - go.transform.position).sqrMagnitude)
    // Get the first element
        .First();

    target.transform.position = closest.transform.position;

    return closest;
 }

这篇关于我想自动找到敌人并将目标放在最近的敌人身上.统一 3D的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆