【问题标题】:How do I make an object detect the nearest specific object in c#?如何让对象检测到 C# 中最近的特定对象?
【发布时间】:2020-10-03 05:31:23
【问题描述】:

假设在某个神奇的土地上有一个圆圈,有3个正方形。一个很近,一个很远,一个在中间。圆圈感觉跑不了那么多,所以他想靠近最近的广场。我将如何在统一 c# 中做到这一点?

【问题讨论】:

  • 如果实体的数量较少,则使用列表而不是通过Vector2.Distance 循环遍历它,如果它有很多,则使用 Culling Group api:docs.unity3d.com/Manual/CullingGroupAPI.html。我也很确定这是重复的,如果你看,你会找到答案

标签: c# unity3d


【解决方案1】:
// assuming Square is a MonoBehaviour
private Square FindClosestToPoint(Vector3 point, params Square[] allSquares) {
    if (allSquares == null || allSquares.Length == 0)
        return null;
    if (allSquares.Length == 1)
        return allSquares[0];
    float distToClosest = float.MaxValue;
    int indexOfClosest = 0;
    for (int i = 0; i < allSquares.Length; i++) {
        Vector3 squarePos = allSquares[i].transform.position;
        float distanceToSquare = Vector3.Distance(point, squarePos);
        if(distanceToSquare < distToClosest) {
            distToClosest = distanceToSquare;
            indexOfClosest = i;
        }
    }
    return allSquares[indexOfClosest];
}

从 MonoBehaviour 调用类似于

Square[] allAvailableSquares = [...] // implement logic on how to get the squares
Square closest = FindClosestToPoint(transform.position, allAvailableSquares);

【讨论】:

    猜你喜欢
    • 2018-09-09
    • 2018-03-12
    • 2020-05-16
    • 1970-01-01
    • 1970-01-01
    • 2020-11-20
    • 1970-01-01
    • 2020-10-17
    • 1970-01-01
    相关资源
    最近更新 更多