0
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ How about use hash table to store chunk data instead of arrays? \$\endgroup\$
    – Mangata
    Apr 16, 2022 at 16:50
  • \$\begingroup\$ How would that make a difference in getting the index for a given position? \$\endgroup\$
    – CitiZen
    Apr 16, 2022 at 18:21

1 Answer 1

0
\$\begingroup\$

This is just basic division.

int column = floorToInt((x - minX) / 20f)
int row = floorToInt((y - minY) / 20f)

int chunkIndex = rowCount * column + row

minX and minY are the coordinates of the bottom-left chunk in your grid, so -40 each in this example.

\$\endgroup\$
3
  • \$\begingroup\$ This checks out, thank you! If you don't mind, could you explain the magic numbers (for future reference and other world sizes)? The 4 is the width of the world (num chunks), but how did you arrive at 2? If my world is 100x100, what's the number two then? 2.5 (half width)? \$\endgroup\$
    – CitiZen
    Apr 16, 2022 at 22:00
  • \$\begingroup\$ Revised to show where those +2s come from. \$\endgroup\$
    – DMGregory
    Apr 16, 2022 at 23:58
  • \$\begingroup\$ Thank you. Lovely, clean, and embarrassingly simple :) \$\endgroup\$
    – CitiZen
    Apr 17, 2022 at 0:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .