Grid Snapping System - Top Down 2d GAme

Hi Unity Community!

I have a question about finding a way to snap our 3d objects or 2d Images to a grid system in Unity. Kinda like you would in these games where you build your own town ect… Can someone help on this subject or possibly point me in the right direction.

You’re probably going to have a 2D array holding the imaginary grid. The trickiest part, which isn’t so bad, is mapping grid position to the world and world to the grid.

Suppose your grid is 10x10 (so 0-9 by 0-9.) And suppose each square should be 5x5 is world units, with the corner at world 100,100, making the grid run from 100 to 150 in the world.

Mapping the 0-9 to the world is: worldX = 100 + gridX*5 + 2.5

It starts at 100 on the map, then 5 for each space past the first, then 2.5 to “center” it. So grid#0 has x=102.5, grid#1 has x=107.5 … .

Mapping world 100 to 150 back into the square 0-9 is the same thing backwards with rounding: gridX = Mathf.RoundToInt( (worldX-100-2.5)/5 ). Plus toss in some ifs to be sure it’s between 0 and 9. Then recheck the rounding (to be sure clicking just next to a border is correct.)

So, say to want to explode the contents of grid(3,7). Use the first formula to figure where to put the explosion: (100+15+2.5, 100+35+2.5) Say to have s screen raycast onto the terrain at (124, 109) and want to find the square they are on – use the second: (21.5/5, 6.5/5) = (4,1)

Umm I understand a little bit of that or it makes sense but Im a Animator by trade and so its hard to understand some of it haha Now is this something I use as a component and attach it to a object in the scene so it has these attributes or script running behind it?.

Yeah I am learning programming now so I dont sound dumb and can figure out some of these things on my own. I found out what a 2d array is and now understand what you wrote a little more now. I did a few tutorials and will look into this more. Thanks for your help man I also got a programmer new to my team and maybe I can get him in on this discussion and we can all figure it out together :slight_smile: