How do I efficiently choose the terrain chunks to render based on the player position?

Well, I have an array with all the terrains. How do I render them? I just add them to a List of terrains that are sent to the Renderer. There, every terrain of the list is rendered.

The problem is that if I add all the terrains of the array to the list (let's call it toRenderList), my computer explodes because of the number of terrains.

What I've tried to achieve it's to add to the list ONLY the terrains that are into a certain range. This is what I've done:

private static Terrain[][] terrains;
private List<Terrain> toRenderList;
private static final int NUMBER_CHUNKS = 3; //Number of terrains that are added to the list.

public void update(Player player){
if(player.hasChangedTerrainPosition()){
toRenderList.clear();
for(int x = player.getTerrainPosition()[0]-NUMBER_CHUNKS;
x == player.getTerrainPosition()[0]+NUMBER_CHUNKS; x++){
for(int y = player.getTerrainPosition()[1]-NUMBER_CHUNKS;
y == player.getTerrainPosition()[1]+NUMBER_CHUNKS; y++){
}
}
}
}


Just to clarify, the method player.getTerrainPosition returns a int[] with the current terrain coords in where the player is standing. The method player.hasChangedTerrainPosition returns true if the player has changed of terrain.

The problem of this method is that for example if the player is in the position [0,0] it pops an error of ArrayIndexOutOfBounds because of a negative number.

I don't know if I've been specific. This is more basic Java than GamePrograming, but any help will be appreciated. Thanks!

• Have you had a look at quad- or oct-trees? – Niels Mar 8 '16 at 8:15

Treat all the chunks around player, as offsets (shown in one axis but applies for both):

-3 -2 -1 0 +1 +2 +3 <- 7 offsets for 1 axis; for x * y that would be 49 offsets.

0, 0 is the offset where the player is - the origin of "player space". 3, -2 might be roughly to the northeast or whatever, depending on your coordinate system setup, and so forth.

Now we add each of these coordinates to the player's actual position

coords = player.getTerrainPosition() + offset

Lastly, we need to ensure coords are in terrain array range(s). So for example if I was standing at x=1 and was adding an offset of -3 then coords == (-2, y). We can't have any negative values like this, because then you get array indexing errors.

To not show outside world bounds, simply check for any negative coordinates and then do not use them to add a new terrain chunk! In this case any negative value, either x or y, is invalid.

To wrap around on world bounds for each axis x and y, modify coords one more time:

if (offset.x < 0)
offset.x += terrainArrayWidth;
else
{
if (offset.x >= terrainArrayWidth)
{
offset.x -= terrainArrayWidth;
}
}


You are not clearing the list before you add new chunks. Tyy adding terrainList.clear() at the start of the update method.