Dragon20C
Dragon20C

Reputation: 361

Godot - How can I make my chunks generate around the player in a 3 by 3 grid

How can I generate chunks in a 3 by 3 grid so that there is always 9 grid instances in the scene? Currently I only have 1 chunk generating every time the player moves to a new area/chunk.

To make it easier for you guys I put it into a github repo so you guys can download and try it! https://github.com/Dragon20C/GODOT---Flat-Terrain-Generation

Relevant code:

    var chunk_x = floor(player.translation.x / chunk.size)
    var chunk_z = floor(player.translation.z / chunk.size)
    var new_chunk_pos = Vector2(chunk_x, chunk_z)
    
    if new_chunk_pos != chunk_pos:
        if !new_chunk_pos in previous_chunks:
            chunk_pos = new_chunk_pos
            var instance = chunk_scene.instance()
            add_child(instance)
            instance.chunk_position_set(Vector3(chunk_pos.x * chunk.size,0,chunk_pos.y * chunk.size))
            previous_chunks.append(chunk_pos)

Upvotes: 0

Views: 1021

Answers (1)

Theraot
Theraot

Reputation: 40315

Extract this code into a new function:

        if !new_chunk_pos in previous_chunks:
            chunk_pos = new_chunk_pos
            var instance = chunk_scene.instance()
            add_child(instance)
            instance.chunk_position_set(Vector3(chunk_pos.x * chunk.size,0,chunk_pos.y * chunk.size))
            previous_chunks.append(chunk_pos)

Then call it passing new_chunk_pos And the positions of the chunks around it. That is the positions with x in the range from new_chunk_pos.x - 1 to new_chunk_pos.x + 1 and with y in the range from new_chunk_pos.y - 1 to new_chunk_pos.y + 1.

Upvotes: 0

Related Questions