Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Question use DrawRay to calculate the row and column of a cell in a grid

Discussion in 'Scripting' started by julien83franceschi, Apr 11, 2024.

  1. julien83franceschi

    julien83franceschi

    Joined:
    Nov 14, 2020
    Posts:
    242
    Hi everyone,

    I'm trying to put 1's in my 8x8 grid (int [, ] grid) where the pentamino X has been dropped (in the grid).
    The rest (empty cells) are worth 0.
    I use a RayCast that starts from the center of the pentamino and goes down to touch the grid planes and find out which grid cell has been touched (from 0 to 63).
    To do this, I use the following code:

    Code (CSharp):
    1.     void OnMouseUp()
    2.     {
    3.         UpdateRowAndCol();
    4.         UpdateGridWithPentaminoX(row, col); // Mettre à jour la grille avec les valeurs de ROW et COL
    5.         PrintGrid();
    6.         PrintGrid2();
    7.         PrintGrid();
    8.     }
    9.  
    10.     int index;
    11.     void UpdateRowAndCol()
    12.     {
    13.         Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    14.         RaycastHit hitInfo;
    15.         if (Physics.Raycast(ray, out hitInfo, Mathf.Infinity, layerMask))
    16.         {
    17.             if (hitInfo.collider.gameObject != gameObject)
    18.             {
    19.              
    20.                 if (int.TryParse(hitInfo.transform.gameObject.name, out index))
    21.                 {
    22.                     row = (index - 1) / 8; // Mettre à jour row
    23.                     col = (index - 1) % 8; // Mettre à jour col
    24.                     if (col == 0)
    25.                     {
    26.                         col = 8;
    27.                     }
    28.                 }
    29.             }
    30.         }
    31.     }
    32.  
    33.     void Update()
    34.     {
    35.         Ray ray = new Ray(transform.position, Vector3.down);
    36.         if (Physics.Raycast(ray, out hit))
    37.         {
    38.             Debug.DrawRay(cube.transform.position, Vector3.down * 20, Color.green);
    39.             Debug.Log("HIT: Plan touché = " + hit.transform.gameObject.name + ", Row = " + row + ", Col = " + col);
    40.         }
    41.         else
    42.         {
    43.             Debug.DrawRay(cube.transform.position, Vector3.down * 20, Color.red);
    44.             Debug.Log("Le rayon ne touche pas d'objet.");
    45.         }
    46.     }
    47.  
    48.  
    49.     void UpdateGridWithPentaminoX(int row, int col)
    50.     {
    51.         for (int i = 0; i < 5; i++)
    52.         {
    53.             for (int j = 0; j < 5; j++)
    54.             {
    55.                 if (pentaminoX[i, j] == 1)
    56.                 {
    57.                     // Vérifier si les coordonnées sont à l'intérieur des limites de la grille
    58.                     if (row + i >= 0 && row + i < 8 && col + j >= 0 && col + j < 8)
    59.                     {
    60.                          grid[row + i, col + j] = 1;
    61.                     }
    62.                 }
    63.             }
    64.         }
    65.     }
    66.  
    67.     void PrintGrid()
    68.     {
    69.         string gridStr = "Grid:\n";
    70.         for (int i = 0; i < 8; i++)
    71.         {
    72.             for (int j = 0; j < 8; j++)
    73.             {
    74.                 gridStr += grid[i, j] + " ";
    75.             }
    76.             gridStr += "\n";
    77.         }
    78.         Debug.Log(gridStr);
    79.         Debug.Log("HIT: Plan touché = " + hit.transform.gameObject.name + ", Row = " + row + ", Col = " + col);
    80.     }
    The problem is that Debug.Log() always returns 0 in the Row and Col.
    Here's how to set up Debug.Log():
    Debug.Log("Row = " + row + ", Col = " + col); (they are calculated in void UpdateRowAndCol())
    But it still returns 0.
    Here's an image showing pentamino X and its raycast (the latter is red but when it encounters a grid plane it turns green (see void Update) and returns a number from 0 to 63 (the names of small planes that form the grid). The small planes that form the red grid have a size of 1.6f (like the pentamino cubes).



    Thanks for your help,

    A+
     
  2. dstears

    dstears

    Joined:
    Sep 6, 2021
    Posts:
    152
    It may help to add Debug.Log statements in each of the "if" statements of UpdateRowAndCol to see if you are actually reaching the row and column calculation.
    It would also be a good idea to print out hitInfo.transform.gameObject.name to see if you are hitting the expected object.
     
    Kurt-Dekker likes this.
  3. julien83franceschi

    julien83franceschi

    Joined:
    Nov 14, 2020
    Posts:
    242
    Hi everyone,

    I was inspired by this little program (to calculate the 0's and 1's in the grid):



    The only problem is that it doesn't display a 1 on all the parent cubes (it does set the parent to 0).

    Here is the code, can you help me:

    Code (CSharp):
    1. [ExecuteAlways]
    2.  
    3.     int z, x;
    4.  
    5.     public Transform[] Figures;
    6.  
    7.     private void OnValidate()
    8.     {
    9.         grid = new int[8, 10];
    10.     }
    11.  
    12.     private void Update()
    13.     {
    14.         var changedFigures = Figures.Where(i => i.hasChanged);
    15.  
    16.         if (changedFigures.Count() != 0)
    17.         {
    18.             ResetGrid();
    19.  
    20.             foreach (var figure in changedFigures)
    21.             {
    22.                 foreach (Transform box in figure)
    23.                 {                  
    24.                     int x = Mathf.FloorToInt((box.position.x / 0.8f) * 0.8f);
    25.                     int z = Mathf.FloorToInt((box.position.z / 0.8f) * 0.8f);
    26.  
    27.                     if (PositionIsValid(x, z))
    28.                     {
    29.                         grid[z, x] = 1;
    30.                     }
    31.                 }
    32.             }
    33.         }
    34.     }
    35.  
    36.     private void ResetGrid()
    37.     {
    38.         for (int z = 0; z < GridSizeZ; z++)
    39.         {
    40.             for (int x = 0; x < GridSizeX; x++)
    41.             {
    42.                 grid[z, x] = 0;
    43.             }
    44.         }
    45.     }
    Also, I'd like it if you drop a pentamino in the top left corner, then the 0s and 1s update in the top left.

    Here's a video with more details:



    Thanks for your help,

    A+
     
  4. julien83franceschi

    julien83franceschi

    Joined:
    Nov 14, 2020
    Posts:
    242
    Hello everyone,

    Here is the problem I am having:
    in the following tuto:



    the program works well, but only if the pentominoes have a size of 1f, whereas I use 1.6f pentominoes and this completely changes the grid update and puts 1s everywhere.

    Perhaps by changing the following code:

    Code (CSharp):
    1.  int x = Mathf.FloorToInt((box.position.x / 1.6f) * 1.6f);
    2. int z = Mathf.FloorToInt((box.position.z / 1.6f) * 1.6f);
    3.  
    in the following code:
    Code (CSharp):
    1.     private void Update()
    2.     {
    3.         var changedFigures = Figures.Where(i => i.hasChanged);
    4.  
    5.         if (changedFigures.Count() != 0)
    6.         {
    7.             ResetGrid();
    8.  
    9.             foreach (var figure in changedFigures)
    10.             {
    11.                 foreach (Transform box in figure)
    12.                 {
    13.                     int x = Mathf.FloorToInt((box.position.x / 1.6f) * 1.6f);
    14.                     int z = Mathf.FloorToInt((box.position.z / 1.6f) * 1.6f);
    15.  
    16.                     if (PositionIsValid(x, z))
    17.                     {
    18.                         grid[z, x] = 1;
    19.                     }
    20.                 }
    21.             }
    22.         }
    23.     }
    24.  
    Your help is most welcome,

    A+
     
  5. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,153
    I'm not going to help you (with regard to your specific questions), mostly bc I don't have time right now, but I still wanted to share some general knowledge on the subject.

    First of all you want to split your logic into a) model, and b) representation. You already have a model (to an extent) by having a 0/1 representation of the grid so you know which cell is occupied and which one is vacant. All state evaluation should query the model (for performance and accuracy), while the representation (incl. UI) should strictly maintain synchronization.

    In your case it makes sense to feed input from representation via ray casts, but there are many ways this can be done as well.

    When it comes to grid behavior (in a continuous space), what you're doing here is a transformation that is known as Xstep where X is a floor/ceil/round type of behavior and step denotes that the result is mathematically a step function (i.e. discontinuous). It is useful to stay on top of these things by clumping such transformations in bite size operations.

    Here's how I defined all three
    Code (csharp):
    1. /// <summary> Rounds down floating point value to the first lesser regular interval. </summary>
    2. static public float floorStep(float n, float d, float o = 0f)
    3.   => d == 0f? n : d * System.MathF.Floor((n - o) / d + o;
    4.  
    5. /// <summary> Rounds up floating point value to the first greater regular interval. </summary>
    6. static public float ceilStep(float n, float d, float o = 0f)
    7.   => d == 0f? n : d * System.MathF.Ceiling((n - o) / d) + o;
    8.  
    9. /// <summary> Rounds floating point value to the nearest regular interval. </summary>
    10. static public float roundStep(float n, float d, float o = 0f)
    11.   => d == 0f? n : d * System.MathF.Round((n - o) / d) + o;
    where n = value, d = grid step, o = grid's zero offset

    Now when you have this you can define a compound Vector2 variant.
    For this I usually make ForEach helpers (inside a static class)

    Code (csharp):
    1. static public Vector2 ForEach(this Vector2 v, Func<int, float, float> lambda)
    2.   => new Vector2(lambda(0, v[0]), lambda(1, v[1]));
    And now you can do
    Code (csharp):
    1. static public Vector2 roundStep(Vector2 v, Vector2 grid, Vector2 origin = default)
    2.   => v.ForEach( (i,v) => roundStep(v, grid[i], origin[i]) );
    Now if you need to run this on XZ, you need some more helpers
    Code (csharp):
    1. static public Vector2 v2_xz(Vector3 v) => new Vector2(v.x, v.z);
    2. static public Vector3 v3_xz(Vector2 v, float y = 0f) => new Vector3(v.x, y, v.y);
    Finally
    Code (csharp):
    1. var grid = new Vector2(1.6f, 1.6f);
    2. box.transform.localPosition = v3_xz(roundStep(v2_xz(box.transform.localPosition), grid));
    Is one way of sorting this out. You can do a similar thing for ints if you use Vector2Int. For example

    Code (csharp):
    1. var grid = new Vector2(1.6f, 1.6f);
    2. var (x, z) = v2int(roundStep(v2_xz(box.transform.localPosition), grid)).AsTuple();
    where
    Code (csharp):
    1. static public Vector2Int v2int(Vector2 v) => new Vector2Int((int)v.x, (int)v.y);
    2. static public (int x, int y) AsTuple(this Vector2Int v) => (v.x, v.y);
    Maybe this is not your final production code (it's sometimes advantageous to lower it for better speed and compiler optimization), but it's immensely good for prototyping, nearly all equations are single-line, can be glanced over, and you are flexible and unlikely to produce errors by omission or needless repetition. Also vectors are packed as single entities (which they logically are), so you don't need to constantly pack and unpack their constituents and repeat the same formulas over and over, which is especially important when working in 3D.

    Additionally, when you adapt your coding style to micro-libraries and helpers that suit you, you can very easily migrate existing computation to something like Unity Mathematics or shader code.

    I apologize in advance if you can't do anything with this information for your particular problem, I just thought to share a different approach to your text book example.

    Alternatively, you can bake all of this into a dedicated function that does it all
    Code (csharp):
    1. var grid = new Vector3(1.6f, 0f, 1.6f);
    2. var (x, _, z) = getIndiceFromPosition(box.transform.localPosition, grid);
    3. // here you can use x and z like normal variables
    4.  
    5.  
    6. (int x, int y, int z) getIndiceFromPosition(Vector3 p, Vector3 grid, Vector3 origin = default) {
    7.   return ( roundStepInt(0), roundStepInt(1), roundStepInt(2) );
    8.  
    9.   int roundStepInt(int i) // this local function makes use of by ref capturing
    10.     => (int)(grid[i] == 0f? p[i]
    11.           : grid[i] * System.MathF.Round((p[i] - origin[i]) / grid[i]) + origin[i]);
    12. }
    I guess my point is that the more you encapsulate complex operations the more you can build on top of that with less errors. Makes you more agile and you can solve your issues faster, even if you're lazy.

    Edit:
    Btw conversion to ints doesn't work properly if your grid is set to decimal values. Grid values must consist of natural numbers (read: positive integers) exclusively for that to work. This is all just a thought experiment.
     
    Last edited: Apr 14, 2024