【问题标题】:Getting the cells in a grid between 2 positions在两个位置之间的网格中获取单元格
【发布时间】:2023-03-18 01:10:01
【问题描述】:

我有一个网格,我想在其中获取我用鼠标拖动的区域中的所有单元格,即 mouseDown 和 mouseUp 之间的所有单元格。

我尽了最大努力,但无法想出一个适用于正值和负值的解决方案。

假设我有这个网格,红点是鼠标事件:

我开始编写一个函数来获取该区域中的所有单元格,但在考虑负数(向下和向左拖动)和正数(向上和向右拖动)时,我似乎无法弄清楚如何做到这一点) 值。

public static Vector2Int[,] GetAreaBetweenPositions(Vector2Int mouseDown, Vector2Int mouseUp)
    {
        int diffX = mouseUp.x - mouseDown.x;
        int diffY = mouseUp.y - mouseDown.y;

        Vector2Int[,] area = new Vector2Int[diffX, diffY];

        for (int x = mouseDown.x; x < diffX; x++)
        {
            for (int y = mouseDown.y; y < diffY; y++)
            {
                area[x, y] = new Vector2Int(mouseDown.x + x, mouseDown.y + y);
            }
        }

        return area;
    }

【问题讨论】:

  • 你没有说你正在使用什么平台,但是,“大多数”网格都有一个“选定的”单元格集合。从而消除所有发布的代码。
  • @JohnG 不太清楚你的意思。我对这个数学问题的解决方案感兴趣,平台应该无关紧要吗?可能是我误会了

标签: c# unity3d math


【解决方案1】:

虽然我尚未对此进行全面测试,但我想我找到了解决方案:

public static Vector2Int[,] GetAreaBetweenPositions(Vector2Int mouseDown, Vector2Int mouseUp)
{
    int dirX = mouseUp.x > mouseDown.x ? 1 : -1;
    int dirY = mouseUp.y > mouseDown.y ? 1 : -1;

    int diffX = Mathf.Abs(mouseUp.x - mouseDown.x);
    int diffY = Mathf.Abs(mouseUp.y - mouseDown.y);

    Vector2Int[,] area = new Vector2Int[diffX + 1, diffY + 1];

    for (int x = 0; x < area.GetLength(0); x++)
    {
        for (int y = 0; y < area.GetLength(1); y++)
        {
            area[x, y] = new Vector2Int(mouseDown.x + (x * dirX), mouseDown.y + (y * dirY));
        }
    }
    
    return area;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-27
    • 2011-10-01
    • 2012-08-19
    • 2016-07-12
    • 2013-06-07
    • 1970-01-01
    • 2020-01-02
    相关资源
    最近更新 更多