detect collision for every rect in a mesh

// to give vertices, uvs, triangles, and colors
for (int x = 0; x < 50; ++x)
for (int z = 0; z < 50; ++z)
FillRect(x, z);

// layout all rects onto a mesh
Mesh mesh = new Mesh();
mesh.vertices = vertices;
mesh.uv = uvs;
mesh.triangles = triangles;		
mesh.colors = colors;
mesh.RecalculateNormals();
GetComponent<MeshFilter>().mesh = mesh;	

As you can see in the picture below,
I have a yellow cube located in the middle of a large mesh which includes 50 * 50 amount of Rects inside(dynamically created by the code above).

How I can detect collision event(the cube collides a Rect) when the cube move around(causes in different position) in this mesh?

thanks ~

13099-collision1.jpg

If you’re asking how you can tell what pair of triangles (a “quad,” if you can even call it that, in Unity) that the square is on at any given time, and that is the reason you have this grid-like mesh designed this way, your’e going at it all wrong.

There’s a number of simple ways you could do this, and I would strongly suggest -not- using mesh colliders. Those will get ridiculously complex and laggy very quickly, if you’re trying to detect positions on a large 2D grid (or even a not-so-large grid :stuck_out_tongue: it’s just bad practice, trust me).

The simplest method to accomplish this task would be to use individual box colliders on each “square” of the field, or to use Physics.CheckSphere on each square in the field. I would suggest the former, as the latter can get fairly expensive fairly quickly.

Another method would be to track the unit’s position in a simple monobehaviour, based on the size of the grid’s increments. In other words, if each unit along the grid is, say, 5 normal unity units in length, and 5 in width, then simply take the box’s position in space, divide it by 5, then add half the number of spaces on the grid’s x axis to the x-coordinate, and half the number of spaces on the grid’s y-axis to the y-coordinate.

For example: if you have a board that is 10 squares by 10 squares, and each square has a length and width of 5 units, and your box’s position in 3d space (in Unity units) is, say, (15,15,0), then the position in GRID space would be ((15/5) + 5,(15/5) + 5), or (8,8), so the eighth column and the eighth row of the grid. If you want your grid to be able to utilize negative numbers, you don’t have to add the 5 to either parameter, as that is simply handling the offset, since Unity’s grid is centered at (0,0), usually.

As for having triggered events based on this value, you could check each frame in an update method of some monobehaviour whether the square is within some specific point on the grid. This may or may not be more taxing on the system than using an array of trigger-colliders, depending on how big your grid is. I would strongly suggest this method over the first, with larger grids.