I'm coding a puzzle game where you can slide the tiles horizontally or vertically in a 3x3 gridmap.
If you select a tile, when you press up or down arrow key, the column this selected tile is in moves vertically upwards or downwards by 1 unit. Same applies to horizontal movements.
This will cause the blocks to go over the 3x3 boundary. This is why I have another rule that: when a block is over the 3x3 boundary, it is teleported to the vacant position, filling the grid map. So, for example: the horizontal order of blocks could be (1, 2, 3). After sliding this row of blocks to the left by 1 grid, the order becomes (3, 1, 2). Do it again? It is (2, 3, 1). Here's a screenshot of what the level looks like:
I thought it was a really simple logic to code but it has proven me wrong. It is actually fairly tricky.
I initially assigned each block an order number exactly identical to that of the keypad. So, bottom left block would be 1, then 2 on the right, and 3 on the bottom right... Whenever I pressed number key 1 on keypad and pressed up arrow, I hard-coded it and set the vertical order of blocks (1, 4, 7) to (7, 1, 4).
It doesn't work at all because if I don't reset the position back to normal, and start to change another given row or column, the layout of the map becomes messed up. This is because even if I changed the physical position of the blocks, their assigned order is not changed, which means that if the blocks that are going to be moved are not in their normal position, they can overlap onto other blocks.
Anyways, here is an example of the designed mechanic:
I. Normal position:
II. Slided row (1, 2, 3) right by 1 unit
III. Slided column (2, 5, 8) downwards by 1 unit
Can someone please give me some advice? It doesn't have to be in actual code. I just need some directions to go for... I'm out of ideas now.




As pointed out your images are not quite accurate ^^
Anyway, there might be more efficient and extendable ways but here is what I would do as a first iteration - plain straight forward:
Have a grid component which holds a 3x3 grid and handles all the shift operations
Additionally I will also route all movements through this
Gridcomponent in order to easily move tiles together - entire rows or columns - and keep things cleanI hope the comments are clear enough
And then accordingly have a
GridElementcomponent on each grid element to handle the dragging and route the movement through theGridFinally in order to make this setup work you will need
EventSystemcomponent anywhere in your scenePhysicsRaycastercomponent on yourCameraLittle demo