Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question Getting rectangle of grid cells between to coordinates

Discussion in 'Scripting' started by Jugro, Nov 17, 2022.

  1. Jugro

    Jugro

    Joined:
    Nov 7, 2022
    Posts:
    1
    Hey guys,

    I'm kinda stuck with finding all cells of a grid between two coordinates.
    I've come to a point where I can select a line from a to b using a lerp like that:



    But what I really want is selecting all grid cells between the vectors in a rectangle:




    Can someone point me in the right direction? I fell like spending hours but the most I can do is some bad hacks which work more or less.

    Thank you!
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,620
    What does "selecting" mean? If you only want the X and Y and not use a Vector2Int then I'm not sure what the confusion is.

    X goes from startPosition.x to endPosition.x and Y goes from startPosition.y to endPosition.y
     
  3. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,620
    Maybe you mean something like this:
    Code (CSharp):
    1. // Find the min/max.
    2. var min = Vector3Int.Min(startPosition, endPosition);
    3. var max = Vector3Int.Max(startPosition, endPosition);
    4.  
    5. // Iterate them all.
    6. for(var x = min.x; x < max.x; ++x)
    7. {
    8.    for(var y = min.y; x < max.y; ++y)
    9.    {
    10.        // Do something.      
    11.    }
    12. }
     
    AnimalMan likes this.
  4. NFinfinity

    NFinfinity

    Joined:
    Aug 2, 2021
    Posts:
    2
    A note to anyone who finds this later: I think the code above has an infinite loop in the 8th line. Var y (not X)should be less than max.y, otherwise the second loop will never reach max.y.

    for(var y = min.y; y < max.y; ++y)

    1. // Find the min/max.
    2. var min = Vector3Int.Min(startPosition, endPosition);
    3. var max = Vector3Int.Max(startPosition, endPosition);

    4. // Iterate them all.
    5. for(var x = min.x; x < max.x; ++x)
    6. {
    7. for(var y = min.y; x < max.y; ++y)
    8. {
    9. // Do something.
    10. }
    11. }