I have a world which is divided in chunks and saved in a flattened 2d array. The world is currently 80 units wide and high, and each chunk represent a 20x20 unit area.
This gives that in my flattened chunk array I have the following chunks:
Index 0 x: -40, y: -40 Index 1 x: -40, y: -20 Index 2 x: -40, y: 0 Index 3 x: -40, y: 20 Index 4 x: -20, y: -40 ... Index 10 x: 0, y: 0
Etc. It can be visualized like this (chunk index)
3, 7, 11, 15 2, 6, 10, 14 1, 5, 9, 13 0, 4, 8, 12
The flattening is done column first.
I now want to find the chunk index of a given world position, say x:4 and y:2, or x:-15 and y:5.
I know that I can loop through each row and column and find the first chunk which area covers the given position, but I would like to know if there's a mathematical function to solve this so I can compare it's performance to looping. My solution might fall apart as I scale up the world, as this calculation could be done very often (multiplayer game).
I know I can get the index of a position in a flattened array of positions given the formula (y * width) + x, but this is not applicable here since each index represents a range of positions.