rows and columns of a cell in a grid

Hello to all,

I have created a grid (5x7) composed of several small planes (1.6f length and width each) of which I recovered the name (here it will be a number (see in the image below)).

What I’m looking for is to retrieve the row and column of the box that has been clicked.
Here it would be if we click on the box 27, then the code must return the row(3) and the column (6) of the box.

Here is my code (with a cube on top that sends a raycast to the grid):

    void Update()
    {
            Debug.DrawRay(cube.transform.position, Vector3.down * 10, Color.red);
            RaycastHit hit;
            Ray ray = new Ray(cube.transform.position, Vector3.down);
            if (Physics.Raycast(ray, out hit))
            {
               print(hit.transform.gameObject.name);
            }
    }

My question is how to get the row and column values of the box that was clicked (here 27).
Here is most explicit :

Thanks for your help,

A+

When you make it, put a little MonoBehaviour on it telling its coordinates. Doesn’t have to be much, just something with public integers for column / row.

Otherwise you can use math to figure it out:

  • subtract the zero datum (what you consider “center”)
  • divide each coordinate by the size of the cell (center spacing)
  • cast it to integer

Hi,

Sorry I don’t understand the description of the mathematical formula.

Can you give me some code so I can understand the formula better.

Thanks,

A+

For each axis in question (X and Y):

float worldPositionX = ... from the raycast above

worldPositionX -= CenterX;  // wherever you consider the "zero" line of the cells

worldPositionX /= CellXSize;  // center spacing of cells

int cellX = (int)worldPositionX;

Do that for X and do that for Y. If you’re unclear on the process, feed some values into the above to see it in action.

Although it’s always better to just put a MonoBehaviour on each one:

using UnityEngine;

// @kurtdekker - put one of these on each cell, fill it out with X/Y cell values
//
// when you click on one, use GetComponent<T>() to find this Component, and if
// it exists, use the across/down values

public class CellCoordinates : MonoBehaviour
{
    public int across;
    public int down;
}

Hello,

I don’t understand what you mean with the following line of code:

float worldPositionX = ... from the raycast above

and what you call CenterX.
Is this what you mean:

CenterX = new Vector3(Rows / 2, 0f, Columns / 2);

Your help is welcome,

A+

You can see a fully functional example in my MakeGeo project.

Look in the Bitmap2Grid scene.

Look at this GridCoordinates class:

This is the grid of items generator:

See lines 75 to 77 for where it adds a GridCoordinates object to each Instantiate-d prefab. Those coordinate Components look like:

8722497--1179525--Screen Shot 2023-01-11 at 7.22.20 AM.png

Hello,

Your code is far too complicated,
I personally use the following code to create a grid:

void CreateGrid()
{    
for (float i = -Lines / 2; i < Lines / 2; i++) 
            for (float j = -Columns / 2; j < Columns / 2; j++)
            {
                Vector3 worldPosition = new Vector3(i, 0, j) * 1.6f;
                var obj = Instantiate(gridCellPrefab, worldPosition, Quaternion.identity, transform);
              
                obj.transform.parent = empty.transform;
                obj.name = "cube" + k;
                k++;
            }
}

And I get the variable k which indicates the value of the box.
But what I’m looking for is to get the row and column of k.

Your code probably works perfectly, but I don’t understand everything.
If you can answer my questions above.

Thanks to you,

A+

Are you joking? This is the code in question:

// demonstration of putting integer cell coorinates
GridCoordinates coordinates = copy.AddComponent<GridCoordinates>();
coordinates.CellX = i;
coordinates.CellY = j;

What part of that don’t you understand?!

And what part of this class don’t you understand:

https://github.com/kurtdekker/makegeo/blob/master/makegeo/Assets/makegridfrombitmap/Bitmap2Grid/GridCoordinates.cs

It’s two (2) public integers in a MonoBehaviour. I’m not sure how much simpler it could be. I don’t think there is anything that could be deleted from the above… it is a total of six or even lines of code combined.

Hello,

Sorry, I don’know why you entered:

GridCoordinates coordinates = copy.AddComponent<GridCoordinates>();

Here is a piece of code

for (float i = -Lignes / 2; i < Lignes / 2; i++)                                                                  
  for (float j = -Colonnes / 2; j < Colonnes / 2; j++)
  {
     CellX = i;
     CellY = j;
  }

As you can see the values of CellX and CellY can have negative values or numbers to the decimal point.
What I am looking for are positive rows and columns.

Thanks for your help,

A+

Hello,

I have tried this code but it doesn’t work:

GridCoordinates coordinates = copy.AddComponent<GridCoordinates>();
coordinates.CellX = i;
coordinates.CellY = j;

You can see it on the picture below:

Thanks again,

A+

Your original post asks how to get row and column.

These are integers, which is why GridCoordinates has integers.

If you want float, then make GridCoordinates be float instead.

I suggest instead that you keep them as integer.

To get integer grid values out of your centered grid, change your loop to:

       int i2 = 0;
        for (float i = -Lignes / 2; i < Lignes / 2; i++)
        {
            int j2 = 0;
            for (float j = -Colonnes / 2; j < Colonnes / 2; j++)
            {
                // TODO:
                /// add a GridCoordinate to this GameObject
                /// use i2 and j2 to set CellX/CellY here

                j2++;
            }
            i2++;
        }

This is just super basic iteration and generation, and I’ve given you several examples now.

If you’re not prepared to do this, just put a single GridCoordinate on each one and set it by hand.

Hello,

Sorry for all the messages, but the formula in the code below sends several errors.

Here is the code:

void CreateGrid()
    {
        float CellX, CellY;
 


        for (float i = -Rows / 2, int i2 = 0 ; i < Rows / 2; i++ , i2++ )
            for (float j = -Columns / 2, int j2 = 0 ; j < Columns / 2; j++ , j2++)
            {
                Vector3 worldPosition = new Vector3(i, 0f, j) * 1.6f;                                                     
                var obj = Instantiate(gridCellPrefab, worldPosition, Quaternion.identity, transform);

                CellX = i2;                                                                                       
                CellY = j2;                                                                                   
    }

And the errors:

Thanks for your help,

A+

line = index / 6 (div) and column = index % 6 (modulo), with index = transform.GetSiblingIndex()

Since VS does not recognise GridCoordinates as a type, you probably did not copy this file to your project, did you?

It seems from everything that Kurt said you only took parts of it.

The point of that small component is that you can attach it to every grid cell gameobject in your grid. Each of those components can hold the row and column of that object. You just need to set them when you create the gameobject. That’s what those 3 lines do. So you instantiate a grid cell object, add a GridCoordinates component to it and set CellX and CellY of that object.

When you raycast against your cell objects, you can use GetComponent to get the GridCoordinates component of the cell object that you hit. Now you can simply read out the CellX and CellY values from that component. That was the main idea behind this approach.

btw: you called the instantiated object “obj” Kurt named his variable “copy”. Since you haven’t changed that in your code shows you haven’t even understood what this was about. Please read the answers carefully and don’t rush over details.

I’m sorry but I don’t understand everything you’re telling me.
What I’m looking for is code that returns the row and column of the box that was clicked on.

For exemple, If you click on the 27th box, the code returns CellX= 3 and CellY= 6;

Thank you,

A+

And you have been given a good method to do so.

To boil it down:

  • Generate a grid of boxes

  • AS YOU GENERATE THEM, assign their x-y values into a component on these boxes

  • When you click on the box, grab this value off the component

Ta-da, there’s your coordinate.

Hi,

Sorry, but your answers do not help me.
It’s simple though, I’m trying to recover CellX and CellY.

Here is the code :

float CellX, CellY;
for (float i = -Lignes / 2; i < Lignes / 2; i++)                                                                 
  for (float j = -Colonnes / 2; j < Colonnes / 2; j++)
  {
     CellX = i;
     CellY = j;
  }

The problem is that CellX and CellY are negative or decimal numbers.

Thanks to you.

Is this a language barrier here? Or do you not understand the coding concepts being explained?

The correct answer has been explained multiple times so far.

Hi,

You are wasting my time,
what I’m looking for is to get the CellX and CellY values of the clicked cell.

I have tried this code:

for (float i = -Lignes / 2, int i2 = 0 ; i < Lignes / 2; i++ , i2++ )

but it points out errors.

Thanks to you,

A+

And you’re being rude and not listening. You can repeat your question all you like but it doesn’t help if you don’t listen.

Then change your logic to be irrespective of their physical position. Their position isn’t the important information here.

Look at the project I so kindly made for another user here: https://forum.unity.com/threads/how-do-i-check-a-gameobjects-position-relative-to-other-gameobjects-positions.1385403/#post-8724579

You can see how I don’t care about the physical position of the boxes at all. I only care about their x and y positions in the blockGrid 2d array, and use BlockGridManager.GetGridPosition() to calculate their position. You can also see how each LetterBlock keeps track of its own position.

With a mere few lines of code you could implement the functionality to click the boxes and read their index positions in the grid. You’re free to give it a crack in the project.