How to make a grid system.
-
Introduction
Grids are very common in lots of games. Expecually in building systems, godot does have built in nodes for this in the form of tilemaps, but this is only good for static tiles that dont do any logic. If you want your tiles to do have more functionality, you cant.
Solutions
There is only really one alternatives to using tilemaps, and that is using nodes directly. But what is thr best way to store these nodes. One solution would be to use a 2D array to store the data, with an empty slot being air/nothing and the other slots being refrences to the nodes at that position in the grid. This system is great, but if you want s large map or infinite terrain this method can be a big problem. Since you have to expand the array wasting lots of memory. The other solution is using a dictionary where the position is key in the dictionary, for example
var grid = {Vector2i(1,1):$stone}
If you want to get the node you could just acces it though grid[pos], and checking if it is a tile or air by grid.has(pos). This method allows you to place a tile anywhere without having to waste memory on air tiles.
If you want infinite terrain you could also make another dictionary for storing the tiles in chunks.
Another problem is tiles that are bigger than 1x1. The best solution is to make more than one refrence to the same tile and when you delete the tile you just delete all the keys in the dictionary related to that tile.
Useful functions
func snap(pos:Vector2): return pos.snapped( Vector2( GRID_SIZE, GRID_SIZE) )
func local_to_grid(pos:Vector2): return snap(pos)/GRID_SIZE
func grid_to_local(pos:Vector2i): return pos*GRID_SIZE
Conclusion
I hope you found this useful. If you still have questions feel free to ask. If you have any suggestions or spelling errors for this post pleasw tell me.
-
-
Could I use both methods at the same time?
Let’s say I used the static Tilemaps for most of a room, but if I wanted to add a secret door (or something along those lines) that has a ton of logic, would I be able to use this Grid System for the door specifically while retaining the Tilemap?
-
Yeah that is true, I cant edit the thread anymore, but for anyone who read the post.
Note the best solution is to use a combination of tilemaps and nodes since tilemaps are extremely optimized and easy to use.